mySQL多连接选择结果作为单行中的列

时间:2013-12-04 09:43:24

标签: mysql sql join

昨天我一直在努力解决这个问题。我已经将连接简化为最低限度,因为它产生了非常奇怪的结果。

现在正在做我期望它做的事情,但不是我想做的事情...理想情况下我想要一行返回day_1,day_2和day_3,如果它们是event_attendee_days中的行。

SELECT event_attendees.id, event_attendees.name, event_account.name AS company,

case event_attendee_days.days_id
when '1' then "25th"
ELSE "-"
end AS day_1,

case event_attendee_days.days_id
when '2' then "26th"
ELSE "-"
end AS day_2,

case event_attendee_days.days_id
when '3' then "27th"
ELSE "-"
end AS day_3,

event_account.email, event_account.telephone, acct_type, acct, address1, address2,     address3, address4, postcode, business_type, business_desc, signup

FROM event_attendees
JOIN event_account ON event_attendees.acct_id = event_account.id
LEFT JOIN event_attendee_days ON event_attendees.id = event_attendee_days.user_id

WHERE event_attendees.id = "1019"

ORDER BY event_attendees.acct_id

目前正在制作(我在这个例子中跳过了不需要的文件。)

id   |   day_1  |   day_2  |   day_3
1019 |   25th   |   -      |   -
1019 |   -      |   26th   |   -
1019 |   -      |   -      |   27th

但我想要

id   |   day_1  |   day_2  |   day_3  | ...
1019 |   25th   |   26th   |   27th   | ...
1020 |   -      |   -      |   27th   | ...

等。我有几个不同的方法,这是我到目前为止最接近的。只需要将结果压缩成一行而不会丢失信息: - )

由于

1 个答案:

答案 0 :(得分:0)

尝试一下:

SELECT
    id,
    MAX(day_1) AS day_1,
    MAX(day_2) AS day_2,
    MAX(day_3) AS day_3
FROM
    event
GROUP BY
    id;

I made an SQL Fiddle here, feel free to test it here

但您仍需要手动输入所需的所有日期。

希望有所帮助

PS:在我的小提琴上,顺便说一句,该表名为“event”,