简体   繁体   English

MySQL 两列一组

[英]MySQL group by two columns

I have a mysql table with the fields id, name, address.我有一个 mysql 表,其中包含字段 id、name、address。 Some entries have identical names but different addresses;有些条目名称相同但地址不同; some have identical addresses but different names.有些地址相同,但名称不同。

I want to get a list including one entry at most for each unique address and one entry at most for each unique name.我想获得一个列表,其中每个唯一地址最多包含一个条目,每个唯一名称最多包含一个条目。

If I could do a group by name then put the results in a temp table and then select again and do a group by address, then I would get exactly what i want - but that seems too complicated.如果我可以按名称进行分组,然后将结果放入临时表中,然后再次 select 并按地址进行分组,那么我会得到我想要的——但这似乎太复杂了。

And doing a "group by name,address" will not give me what I am looking for - that would include entries for all different combinations of name,address whereas I want one entry for each name and one for each address.并且做一个“按名称,地址分组”不会给我我正在寻找的东西 - 这将包括名称,地址的所有不同组合的条目,而我希望每个名称一个条目,每个地址一个条目。 Thanks for your help!谢谢你的帮助!

There's probably a nicer way to do this, and I'm making some assumptions about what you want, but you could try something like this:可能有更好的方法来做到这一点,我正在对你想要什么做一些假设,但你可以尝试这样的事情:

SELECT Name, '' AS Address, Count(Address) AS RowCount
  FROM TableName
  GROUP BY Name
UNION
SELECT '' AS Name, Address, Count(Name) AS RowCount
  FROM TableName
  GROUP BY Address

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

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