使用 Distinct 与 *
我在使用 unique 和 * 时遇到问题。我有一个表作为连接,我正在尝试执行以下语句:
SELECT DISTINCT Name, * FROM table_a JOIN table_a.id=table_b.id WHERE status=1
但它不允许我这样做。有没有办法使用带有 * 选项的 Distinct ?
I am having a problem using distinct with *. I have a table that as a join and I am trying to do a statement like:
SELECT DISTINCT Name, * FROM table_a JOIN table_a.id=table_b.id WHERE status=1
But it is not allowing me to do so. Is there a way of using Distinct with * option?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我现在无权测试这个,但我怀疑问题不在于
distinct
,而是每个表中都有具有相同名称的列(例如id
code>) 并且它不知道选择两个冲突列中的哪一个。如果您选择不同的table_a.*、table_b.* ...
,它会改变吗?I don't have access to test this right now, but I suspect that the problem is not with
distinct
but rather that you have columns in each table with the same names (likeid
) and it doesn't know which of the two conflicting columns to choose. Does it change if you doselect distinct table_a.*, table_b.* ...
?DISTINCT *
可能会返回所有行,因为它们是不同的:-)要获取所有不同的名称,请使用
DISTINCT name
或检索有关名称的一些统计信息(例如计数),请使用 <代码>选择名称,COUNT(*) FROM ...按名称分组。DISTINCT *
probably will return all rows, because they are distinct:-)To get all different names use
DISTINCT name
or to retrieve some statistics about names (e.g. count) useSELECT name, COUNT(*) FROM ... GROUP BY name
.目前尚不清楚你想做什么。
也许您只想返回具有给定名称的一列(而不是两个 id 列)。
在这种情况下,标准的 SQL 查询是这样的:
关键字 DISTINCT 意味着执行 select 后,重复的行被消除(不是重复的列名)。
It is not clear what you want to do.
Maybe you want to return only one column with a given name (not two id columns).
In this case the standard SQL query is like this:
The keyword DISTINCT means that after performing the select, duplicate rows are eliminated (not duplicate column names).
基本上解决方案更像是这样:
如果您想避免枚举属性,这很有用。当您这样做时,并且关系发生变化(删除或添加一个属性),您的查询将不起作用。
阅读此内容:MySQL 8.3.1.13。独特的优化
Basically the solution is more like this:
This is useful, if you want to avoid the enumeration of attributes. When you do, and the relation changes (one attribute is removed or added), your query will not work.
Read this: MySQL 8.3.1.13. DISTINCT Optimization