簡體   English   中英

MySQL多連接選擇結果作為單行中的列

[英]mySQL multiple join select results as columns in single row

我昨天一直在努力處理這個查詢。 我將聯接簡化到最低限度,因為它產生了非常奇怪的結果。

現在它正在執行我“期望”的操作,但不執行我想要的操作...理想情況下,如果它們是event_attendee_days中的行,則我希望返回一行day_1,day_2和day_3。

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   | ...

等等。我有一些不同的看法,這是我到目前為止最接近的。 只需將結果壓縮為一行,而不會丟失信息:-)

謝謝

試試看:

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;

我在這里做了一個SQL Fiddle,請隨時在這里進行測試

不過,您仍然需要手動輸入所有日期。

希望能幫助到你

PS:在我的小提琴上,該表被命名為“事件”

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM