MySQL查询返回重复的行

时间:2016-01-19 21:15:47

标签: mysql sql join

我有一张表mytable,如下所示;

╔═════════╦══════╦═════╗
║ product ║ tag  ║ lot ║
╠═════════╬══════╬═════╣
║ 1111    ║ 101  ║ 2   ║ 
║ 1111    ║ 102  ║ 5   ║ 
║ 2222    ║ 103  ║ 6   ║ 
║ 3333    ║ 104  ║ 2   ║  
║ 4444    ║ 101  ║ 2   ║ 
║ 5555    ║ 101  ║ 2   ║ 
║ 5555    ║ 102  ║ 5   ║ 
║ 6666    ║ 102  ║ 2   ║ 
║ 6666    ║ 103  ║ 5   ║
║ 7777    ║ 101  ║ 2   ║ 
║ 7777    ║ 102  ║ 5   ║ 
║ 7777    ║ 103  ║ 6   ║ 
║ 8888    ║ 101  ║ 1   ║ 
║ 8888    ║ 102  ║ 3   ║ 
║ 8888    ║ 103  ║ 5   ║ 
║ 9999    ║ 101  ║ 6   ║ 
║ 9999    ║ 102  ║ 8   ║
╚═════════╩══════╩═════╝

我有输入101102。我希望输出像;

2,5
6,8

我有一个像<; p>这样的查询

select group_concat(lot order by lot)
from `mytable`
group by product
having group_concat(tag order by tag) = '101,102';

它返回;

2,5
2,5
6,8

而不是两个2,5,我只想要一个,避免重复行。我怎么能这样做?

这是小提琴http://sqlfiddle.com/#!9/7a78bb/1/0

2 个答案:

答案 0 :(得分:6)

如果你想要distinct那么

select distinct group_concat(lot order by lot)
from `mytable`
group by product
having group_concat(tag order by tag) = '101,102';

答案 1 :(得分:0)

您只需使用DISTINCT消除重复

select DISTINCT group_concat(lot order by lot)
from `mytable`
group by product
having group_concat(tag order by tag) = '101,102';