Farzad
Farzad

Reputation: 2090

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

Upvotes: 0

Views: 39

Answers (1)

Jules
Jules

Reputation: 295

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));

Upvotes: 1

Related Questions