MySQL:根据列的值获取记录

时间:2015-10-31 11:58:35

标签: php mysql sql

我在n中有my_table条记录。

我想从表中选择所有记录,因此我使用此查询:

SELECT * FROM `my_table`;

然后我用WHERE子句限制它:

SELECT * FROM `my_table` WHERE id > 30;

cat_name中有一列(my_table),其价值是决定性的。此列的值不是唯一的,因此记录中可能会有很多重复。我想限制记录,以便cat_name的值绝不能的每个值重复四次以上,因此,我想要这样的结果:

+++++++++++++++++++++++++++
id | name       | cat_name
+++++++++++++++++++++++++++
33 + Robert     +  Radio 
34 + Alice      +  Radio 
35 + Jennifer   +  Radio 
36 + Sara       +  Radio 
37 + Maria      +  TV 
38 + Sebastian  +  TV 
38 + Jack       +  TV 
40 + Albert     +  TV
.
.
... the rest of records

但是不幸我得到这个结果因为我不应该怎么做 以这种特定方式限制查询:

+++++++++++++++++++++++++++
id | name       | cat_name
+++++++++++++++++++++++++++
33 + Robert     +  Radio
34 + Alice      +  TV
35 + Jennifer   +  Radio
36 + Sara       +  Radio
36 + Maria      +  Radio
36 + Sebastian  +  TV
36 + Jack       +  Radio
36 + Albert     +  Radio
...

2 个答案:

答案 0 :(得分:1)

我会通过枚举每个cat_name的行然后选择前四个来解决这个问题:

select ci.*
from (select t.*,
             (@rn := if(@c = cat_name, @rn + 1,
                        if(@c := cat_name, 1, 1)
                       )
             ) as rn
      from my_table t cross join
           (select @c := '', @rn := 0) params
      order by cat_name, id
     ) ci
where rn <= 4;

答案 1 :(得分:0)

SELECT * FROM my_table WHERE id&gt; 30 ORDER BY cat_name DESC

https://dev.mysql.com/doc/refman/5.0/en/sorting-rows.html

编辑抱歉,读得太快了。 如果你想限制每组&#39; cat_name&#39;中的行数。 - 我不认为使用mySQL是一种简单的方法。

使用postgreSQL,您可以选择row_number()OVER(PARTITION BY&#34; cat_name&#34;)并按此过滤,但我不知道mySQL中是否有等价物。

所以我建议让PHP过滤数据:

<?php
[...]
$resultarray = [];
$lastgroup = "";
$count = 0;
while($row = $mysqli_fetch_assoc()) {
  if($row['cat_name'] != $lastgroup) {
    $lastgroup = $row['cat_name'];
    $count = 0;
  }
  $count++;
  if($count <= 4) {
    $resultarray[] = $row;
  }
}