当我在mysql中有where子句时,如何选择前几行?

时间:2018-12-04 07:59:58

标签: mysql

我有这个查询来选择带有子句的前8行。但是,如果该子句无效,请返回第9行的下一个值,10,依此类推。我想检查前8行,是否要检查2行不验证该子句仅返回6行..这是我所拥有的查询:

$sql="SELECT * FROM nazir_items_ishop_category WHERE active = 1  order by id_cat asc limit 8";

是否可以仅从前8行询问和接收答案?

服务器MYSQL版本:5.6.41-cll-lve-MySQL社区服务器(GPL)–

1 个答案:

答案 0 :(得分:0)

如果您只想查看前8行,则需要找出它们的id_cat值,然后对发现它们的子查询使用IN

SELECT *
FROM nazir_items_ishop_category
WHERE active = 1 
AND id_cat IN (SELECT id_cat 
               FROM nazir_items_ishop_category 
               ORDER BY id_cat ASC
               LIMIT 8)

如果不能在子查询中使用LIMIT,则可以对派生表使用JOIN

SELECT n1.*
FROM nazir_items_ishop_category n1
JOIN (SELECT id_cat,active 
      FROM nazir_items_ishop_category 
      ORDER BY id_cat ASC
      LIMIT 8) n2 ON n2.id_cat = n1.id_cat AND n2.active = 1