简体   繁体   中英

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

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.

Instead you'll have to evaluate total count in distinct query and combine it with, for instance, 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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