简体   繁体   English

如何在mysql中获取不重复的结果

[英]how to get not duplicated results in mysql

I am trying to get results from mysql by not letting a specific field gets repeated more than 5 times. 我试图通过不让特定字段重复超过5次来从mysql中获得结果。

For example, lets say that I have a table like this : 例如,假设我有一个像这样的表:

-------------
Name        City    
person1     Nashville
person2     Nashville
person3     Nashville
person4     Nashville
person5     Nashville
person6     Nashville
person7     New York
-------------

What I want it to return is this : 我想要它返回的是:

-------------
Name        City    
person1     Nashville
person2     Nashville
person3     Nashville
person4     Nashville
person5     Nashville
person7     New York
-------------

where the city field cannot be repeated more than five times! 不能重复超过五次的城市领域! if it was repeated more than fix times, only return the first five results. 如果重复超过固定时间,则仅返回前五个结果。

This question could be impossible (that is what I am guessing) but if there is a solution or anyway to work around what I am trying to achieve, please tell me! 这个问题可能是不可能的(这就是我所猜测的),但是如果有解决方案或者无论如何都可以解决我要达到的目标,请告诉我! I can use PHP. 我可以使用PHP。

How about something like this which uses variables to check the current row to the previous row, if they are the same then the row number will increase if they are not the row number will reset: 像这样的事情怎么样呢?它使用变量来检查当前行到上一行,如果它们相同,那么如果行号不重置,行号将增加:

select name, city
from
(
  select name, 
    city,
    @row:=(case when @prev=city then @row else 0 end) + 1 as rownum,
    @prev:=city pcity
  from yourtable
  order by city, name
) src
where rownum <= 5

See SQL Fiddle with Demo 参见带有演示的SQL Fiddle

The result is: 结果是:

|    NAME |      CITY |
-----------------------
| person1 | Nashville |
| person2 | Nashville |
| person3 | Nashville |
| person4 | Nashville |
| person5 | Nashville |
| person7 |  New York |
    SELECT x.*
      FROM my_table x 
      JOIN my_table y
        ON y.name <= x.name 
       AND y.city = x.city 
     GROUP 
        BY x.city
         , x.name 
    HAVING COUNT(*) <= 5;

Are you allowed to perform more than one MySql command? 您可以执行多个MySql命令吗? If so, you can try doing two separate calls -- 如果是这样,您可以尝试进行两个单独的呼叫-

SELECT name, city FROM table WHERE city = 'Nashville' ORDER BY name LIMIT 5;
SELECT name, city FROM table WHERE city <> 'Nashville' ORDER BY name;

Someone may need to check on this but the general idea stands. 可能需要检查一下,但总体思路仍然存在。 The only problem with this is your end result would not have the table ordered by name. 唯一的问题是您的最终结果将没有按名称对表进行排序。 Rather, it'd have the people with the city has 'Nashville' first, and then everyone else. 而是要让城市中的人先拥有“纳什维尔”,然后才是其他所有人。

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

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