如何使用内部连接在 SQL 中不包含重复项?

How to not include duplicates in SQL with inner join?

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

好的,快速查看 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;

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