MySqli将IF置于选择查询中

时间:2016-06-02 15:02:23

标签: mysql sql if-statement mysqli

此代码如何转换为正确的查询?有可能吗?
首先,我想检查id IN (55,1454,232,444,10999,223)是否存在行。第二个如果不存在则随机获取行。

 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

1 个答案:

答案 0 :(得分:1)

尝试类似:

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