从连接表中选择所有行作为列

时间:2017-01-19 04:43:55

标签: mysql sql

我在从数据库表中选择行时遇到问题。

表A

Id, name

表B

Id, playingdate, points

表a和b与诸如a.id = b.id

之类的链接相关联

表a的数据

1, john
2, tim

表b的数据

1, 20170101, 3455
1, 20170108, 4532
2, 20170101, 5666
2, 20170108, 4768

所以我想回归

John, 3455, 4532
Tim, 5666, 4768

我如何建立sql select?

3 个答案:

答案 0 :(得分:1)

不确定为什么需要这个,因为积分可能很长:

SELECT A.name, group_concat(B.points)
FROM A
JOIN B ON A.id = B.id
GROUP BY A.name

如果你也问它是在列中,那么它甚至很少使用。但是,如果列固定为:name,20170101,20170108,则SQL将为:

SELECT 
  A.name,
  ifnull(B1.points,0) AS '20170101',
  ifnull(B2.points,0) AS '20170108'
FROM A
LEFT JOIN B AS B1 ON A.id = B1.id AND B1.playingdate = 20170101
LEFT JOIN B AS B2 ON A.id = B2.id AND B2.playingdate = 20170108

答案 1 :(得分:0)

首先在表A和B上使用名称连接group_concat和concat:

 SELECT concat(A.name, ',' , group_concat(B.points)) as  name_points
        FROM A
        left outer join B ON A.id = B.id
        GROUP BY A.id
SELECT A.name, group_concat(B.points) as  points
        FROM A
        left outer join B ON A.id = B.id
        GROUP BY A.id

答案 2 :(得分:0)

以下是您查询的有效解决方案....如果您有任何问题,请告诉我......

set @row1 := 0;
set @row2 := 0;
select a.id,a.name,c.p1,c.p2
from a 
inner join 
(
select b1.id,b1.p1,b2.p2
from 
    (   
    select @row1 := @row1 +1 as r1,b.id ,b.points as p1
    from b
    group by id 
    )b1
inner join 
    (
    select @row2 := @row2 +1 as r2,b.points as p2
    from b
    )b2
on b1.r1+1 = b2.r2
)c on a.id = c.id