如何在MYSQL中的JOIN之后删除重复的列值?

时间:2016-12-11 07:41:44

标签: mysql sql mariadb rdms

我想使用join从多个表中获取数据。 它给出了唯一的行,但是列值是重复的 我无法删除重复的值,所以该怎么做?

这些是我的表

表A

A_ID    A_NAME      
-----   -------
1       ONE         
2       TWO         
3       THREE       

表B

A_ID    B_ID    CAT         
-----   -----   --------
1       1       CRICKET     
1       2       FOOTBALL    
2       3       HOCKEY      
3       4       TENISH      
3       7       BASE BALL   

表C

B_ID    NAME
------  ------
1       ASN
1       MARK
1       JOHN
2       JACKY
3       RAJ
3       SAM

预期输出

A_ID    A_NAME  B_ID    CAT         NAME
-----   ------  -----   -------     ------
1       ONE     1       CRICKET     ASN
                                    MARK
                                    JOHN
                2       FOOTBALL    JACKY
2       TWO     3       HOCKEY      RAJ
                                    SAM
3       THREE   4       TENISH
                7       BASEBALL

查询: -

SELECT   A.A_ID
        ,A.A_NAME
        ,B.B_ID 
        ,B.CAT          
        ,C.NAME
FROM     A,B,C 
WHERE    A.A_ID = B.B_ID 
AND      B.B_ID = C.C_ID 
GROUP BY A.A_ID,B_B_ID;

1 个答案:

答案 0 :(得分:0)

可能 在我看来毫无意义。你可以做这样的输出

A_ID    A_NAME  B_ID    CAT     NAME
 1        ONE    1    CRICKET   ASN
 1        ONE    1    CRICKET   MARK
 1        ONE    1    CRICKET   JOHN
 1        ONE    2    FOOTBALL  JACKY
 2        TWO    3    HOCKEY    RAJ
 2        TWO    3    HOCKEY    SAM
 3       THREE   4    TENISH    
 3       THREE   7    BASEBALL

使用一个非常简单的查询:

select
  a.a_id, a.a_name, b.b_id, b.cat, c.name
from
  table_a a join
  table_b b on b.a_id = a.a_id left join
  table_c c on c.b_id = b.b_id
order by
  a.a_id, b.b_id, c.name

您可以在前端轻松解析此问题。您还可以使用group_concat将具有相同a_id和b_id的名称连接到以逗号分隔的列表。

如果你坚持(需要添加一个人工id才能加入上一行):

set @rank1 := 0;
set @rank2 := 1;
select
  case when t2.a_id is null or t2.a_id <> t1.a_id then t1.a_id else null end a_id,
  case when t2.a_name is null or t2.a_name <> t1.a_name then t1.a_name else null end a_name,
  case when t2.b_id is null or t2.b_id <> t1.b_id then t1.b_id else null end b_id,
  case when t2.cat is null or t2.cat <> t1.cat then t1.cat else null end cat,
  t1.name
from
  (select
    a.a_id, a.a_name, b.b_id, b.cat, c.name, @rank1 := @rank1 + 1 as rank
  from
    table_a a join
    table_b b on b.a_id = a.a_id left join
    table_c c on c.b_id = b.b_id
  order by
    a.a_id, b.b_id, c.name
  ) t1 left join
  (select
    a.a_id, a.a_name, b.b_id, b.cat, c.name, @rank2 := @rank2 + 1 as rank
  from
    table_a a join
    table_b b on b.a_id = a.a_id left join
    table_c c on c.b_id = b.b_id
  order by
    a.a_id, b.b_id, c.name
  ) t2 on t2.rank = t1.rank
order by
  t1.rank
;