繁体   English   中英

如何在带有内部连接的 SQL 中不包含重复项?

[英]How to not include duplicates in SQL with inner join?

我正在尝试列出客户的姓名、姓氏、电子邮件、电话号码、地址和他们要去的节目的标题。 我不应该列出客户的重复姓名,但不幸的是,如果一位客户正在观看不同的节目,他们的姓名会出现两次。 尽管使用了 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;

您不需要按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的原因,记录被重复的事实证明它是一个要聚合的列。

好的,对 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;

我遇到了与您遇到的相同问题的类似查询。 我会这样写:

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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM