grizzly grizzly - 6 months ago 8
MySQL Question

MySqli Put IF in Select Query

How can this code convert to correct query? Is it possible?

first i want check if

id IN (55,1454,232,444,10999,223)
is exists rows. second if not exists get rows by random.

SELECT
id
name
title
FROM
table t
WHERE
id IN (55,1454,232,444,10999,223)

IF count_row(t) == 0 // <-- if for WHERE no result row
SELECT
id
name
title
FROM
table
ORDER BY RAND()
LIMIT 20

Answer

Try something like :

   SELECT id,
          name,
          title
    FROM
          table t
    WHERE
          id IN (55,1454,232,444,10999,223)

    UNION

    SELECT *
    FROM
        table t
    WHERE NOT EXISTS (SELECT id,
                             name,
                             title
                      FROM
                             table t
                      WHERE
                             id IN (55,1454,232,444,10999,223));