连接sql查询来分析值
我有一个包含三列的表 entries
:id、name、display_name
。
我需要使用 join 编写一个查询,它将检查每个名称有多少个 display_names 并仅显示那些具有多个 display_names 的名称。
使用连接编写起来应该相当简单。在我使用下一个查询之前:
SELECT e1.name
FROM entries e1
WHERE (
SELECT COUNT(DISTINCT e2.display_name)
FROM entries e2
WHERE e2.name = r1.name
) > 1;
I have a table entries
with three columns: id, name, display_name
.
I need to write a query with join, which will check how many display_names there is for each name and display only those names, which have multiple display_names.
This should be fairly simple to write with joins. Before I used next query:
SELECT e1.name
FROM entries e1
WHERE (
SELECT COUNT(DISTINCT e2.display_name)
FROM entries e2
WHERE e2.name = r1.name
) > 1;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你不需要加入。
请注意,您可以在having子句中使用别名,因此您也可以借用@Scorpi0和@Widor:
允许这样做的原因是
having
在选择中的所有其他内容之后进行评估完成了。到那时别名的内容就会被知道。您不能在
WHERE
子句中使用此别名,因为它在 MySQL 知道别名中的内容之前运行(或可能运行)。You don't need a join.
Note that you can use an alias in a having clause, so borrowing from @Scorpi0 and @Widor you can also do:
The reason this is allowed is that
having
is evaluated after all the other stuff in the select is done. By that time the contents of the alias will be known.You cannot use this alias in the
WHERE
clause because that runs (or may run) before MySQL knows what in the alias.您不需要联接,HAVING 子句可以为您进行过滤:
You don't need a join, the HAVING clause could do the filter for you: