我正在嘗試列出客戶的姓名、姓氏、電子郵件、電話號碼、地址和他們要去的節目的標題。我不應該列出客戶的重復姓名,但不幸的是,如果一位客戶正在觀看不同的節目,他們的姓名會出現兩次。盡管使用了 DISTINCT 和 GROUP BY,但我仍然得到重復。我應該包括什么才能沒有重復的客戶姓名?
select distinct c.first_name, c.last_name, c.email, c.phone, c.address, s.title
from customer c
inner join ticket tk on tk.customer_id = c.customer_id
inner join `show` s on s.show_id = tk.show_id
group by c.first_name, c.last_name, c.email, c.phone, c.address, s.title
order by c.last_name;
uj5u.com熱心網友回復:
好的,對 mySQL 檔案的快速檢查表明您可以使用 Group_Concat() 來達到您的目的:
select c.first_name, c.last_name, c.email, c.phone, c.address, group_concat(s.title) as Title
from customer c
inner join ticket tk on tk.customer_id = c.customer_id
inner join `show` s on s.show_id = tk.show_id
group by c.first_name, c.last_name, c.email, c.phone, c.address, s.title
order by c.last_name;
uj5u.com熱心網友回復:
我遇到了與您遇到的相同問題的類似查詢。我會這樣寫:
select distinct c.first_name, c.last_name, c.email, c.phone, c.address, s.title
from customer c
left join ticket tk on tk.customer_id = c.customer_id
left join `show` s on s.show_id = tk.show_id
group by c.first_name, c.last_name, c.email, c.phone, c.address, s.title
order by c.last_name;
uj5u.com熱心網友回復:
您不需要按 聚合title,因為正如您所指出的,可能有多個標題。相反,通過以下方式將其洗掉group by并聚合group_concat:
select c.first_name, c.last_name, c.email, c.phone, c.address, group_concat(s.title)
from customer c
inner join ticket tk on tk.customer_id = c.customer_id
inner join `show` s on s.show_id = tk.show_id
group by c.first_name, c.last_name, c.email, c.phone, c.address
order by c.last_name;
您也不需要distinct關鍵字。請記住:如果要按欄位進行聚合,則通常需要避免按欄位進行分組。由于title記錄被重復的事實證明它是一個要聚合的列。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/483439.html
上一篇:postgresql觸發器將json資料插入列并保留剩余欄位
下一篇:SQL查詢連續月份登錄
