如何在连接两个表时避免重复

时间:2022-10-30 20:08:18

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 .

不应重复“喀拉拉邦”的价值。

4 个解决方案

#1


2  

you can user Group concat method.Pls check below query

你可以使用group concat方法。请检查下面的查询

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

#2


1  

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.

只要在test2表中每个jid有一条MIN(名称)的记录,这就会产生所需的结果。

Demo here

在这里演示

#3


1  

try this

尝试这个

SELECT  IF (@oldname = name1,'',name1),
        name2,
        @oldname:=name1 AS oldname FROM
  (
    SELECT t1.name AS name1, t2.name AS name2
    FROM test1 t1
    INNER JOIN test2 t2
    WHERE t1.id = t2.jid
  ) t,
  (SELECT @oldname:='' ) tmp;

#4


0  

I don't think it's possible - you can't have empty values inside returned values.

我不认为这是可能的 - 你不能在返回值中包含空值。

#1


2  

you can user Group concat method.Pls check below query

你可以使用group concat方法。请检查下面的查询

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

#2


1  

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.

只要在test2表中每个jid有一条MIN(名称)的记录,这就会产生所需的结果。

Demo here

在这里演示

#3


1  

try this

尝试这个

SELECT  IF (@oldname = name1,'',name1),
        name2,
        @oldname:=name1 AS oldname FROM
  (
    SELECT t1.name AS name1, t2.name AS name2
    FROM test1 t1
    INNER JOIN test2 t2
    WHERE t1.id = t2.jid
  ) t,
  (SELECT @oldname:='' ) tmp;

#4


0  

I don't think it's possible - you can't have empty values inside returned values.

我不认为这是可能的 - 你不能在返回值中包含空值。