MYSQL SELECT only if rows are less than 5

I have a table called iv6_posts. I want to select records only if records are less than 5 rows; it should be in one query

something like that:

   select IF((select count(*) from iv6_posts)<5,select * from iv6_posts,null)
+4
source share
1 answer

You cannot achieve this with the simple WHERE, as it COUNT()is a group function, and you cannot use plain HAVING, since it will group the lines into one.

Instead, you will have to evaluate the total score in a separate request and combine it, for example 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 .

+1
source

All Articles