Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i avoid duplication while joining two tables

Tags:

join

mysql

i have two tables

  1. test 1

  2. test 2

First table has

**id**  -   **name**

 1      -    kerala 

 2      -    Tamilnadu

Second table

  **name**  -  **jid**

   value 1  -  1

   value 2  -  1

   value 3  -  1

   value 4  -  1

   value 5  -  2

My Query --

SELECT t1.name, t2.name
FROM test1 t1
INNER JOIN test2 t2
WHERE t1.id = t2.jid

now i get this result

**name**    -  **name**

Kerala  -  value 1

kerala  -  value 2

kerala  -  value 3

kerala  -  value 4

But i need a result like this

Kerala  -  value 1

        -  value 2

        -  value 3

        -  value 4

the value ' Kerala ' should not be repeated .

like image 939
Aby Sebastian Avatar asked Sep 27 '22 13:09

Aby Sebastian


2 Answers

you can user Group concat method.Pls check below query

 SELECT t1.name,GROUP_CONCAT(t2.name) FROM test1 t1 INNER JOIN test2 t2 WHERE t1.id = t2.jid
like image 88
Sandeep Nambiar Avatar answered Sep 30 '22 09:09

Sandeep Nambiar


You can use the following query:

SELECT CASE 
          WHEN t2.name = t3.firstName THEN t1.name
          ELSE ''
       END AS name,   
       t2.name
FROM test1 t1
INNER JOIN test2 t2 ON t1.id = t2.jid
INNER JOIN (
   SELECT jid, MIN(name) AS firstName
   FROM test2
   GROUP BY jid) AS t3 ON t2.jid = t3.jid

This will produce the required result as long as there is a single record having MIN(name) per jid in test2 table.

Demo here

like image 32
Giorgos Betsos Avatar answered Sep 30 '22 10:09

Giorgos Betsos