Mysql加入不同的值

时间:2012-07-31 07:35:35

标签: mysql

表名:x

id名称 id是主键

1   xxxx
2   yyyy

表名:y
sno主键 id外键 类

1 1 first 
2 1  second

输出

id 
xxxx first second

我不想为每一行重复名称

SELECT x.name, y.class from x,y  WHERE x.id = y.id

此查询输出为xxxx first和xxxx second

3 个答案:

答案 0 :(得分:3)

添加GROUP BY y.id然后避免重复。

答案 1 :(得分:0)

SELECT x.name, y.class 
FROM x
     LEFT JOIN (SELECT DISTINCT id, class FROM y) y 
        ON x.id = y.id;

答案 2 :(得分:0)

试试这个:

set @yclass:='';
select  a.name,max(class) as class
from
(select @xname:=name as name,@yclass:=concat(@yclass,' ',y.class)  as class
from x join y
on x.id=y.id)a