简体   繁体   English

仅当行小于5时才使用MYSQL SELECT

[英]MYSQL SELECT only if rows are less than 5

i have a table named iv6_posts i want to select records only if records are less than 5 rows it should be in one query 我有一个名为iv6_posts的表我只想在一个查询中记录小于5行时才选择记录

something like this: 这样的事情:

   select IF((select count(*) from iv6_posts)<5,select * from iv6_posts,null)

You can't achieve that with plain WHERE since COUNT() is a group function and you can't use plain HAVING since it will group rows into one. 使用plain WHERE无法实现这一点,因为COUNT()是一个组函数,你不能使用plain HAVING因为它会将行分组为一个。

Instead you'll have to evaluate total count in distinct query and combine it with, for instance, CROSS JOIN : 相反,您必须评估不同查询中的总计数,并将其与例如CROSS JOIN

SELECT
  iv6_posts.*
FROM 
  iv6_posts
    CROSS JOIN 
      (
       SELECT 
         COUNT(1) AS c
       FROM 
         iv6_posts
      ) AS init
WHERE
  c<5

Check the fiddle for it. 检查它的小提琴

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

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