如何将MySQL语句与“IF”结合起来?

时间:2013-10-11 21:35:07

标签: mysql sql

如何使用MySQL将这些组合成一个语句?

SELECT COUNT(barcode) AS count
FROM movieitemdetails_custom
WHERE username = 'John';

if count is == 0

    SELECT title FROM movieitemdetails WHERE barcode = '12345';

else

    SELECT title FROM movieitemdetails_custom WHERE username = 'John';

end-if

3 个答案:

答案 0 :(得分:1)

以下是获取列表的一种方法:

SELECT title
FROM movieitemdetails
WHERE barcode = '12345'
AND (
  SELECT COUNT(barcodes)
  FROM movieitemdetails_custom
  WHERE username = 'John'
) = 0
UNION SELECT title
FROM movieitemdetails_custom
WHERE username = 'John'
AND (
  SELECT COUNT(barcodes)
  FROM movieitemdetails_custom
  WHERE username = 'John'
) > 0

这是一个looong日的结束,所以我希望我的计数为零/非零逻辑:)

顺便说一句,我同意@Max的观点,即downvote是不值得的。我投了这个问题。

答案 1 :(得分:0)

 SELECT CASE WHEN countt = 0 THEN (SELECT barcodes FROM movieitemdetails WHERE username = 'John') 
 ELSE (SELECT barcodes FROM movieitemdetails_custom WHERE username = 'John')

答案 2 :(得分:0)

一个选项是:

SELECT COALESCE(`mdc`.`title`, `md`.`title`, 'NO TITLE') `title`
FROM (SELECT NULL) der
    LEFT JOIN `movieitemdetails_custom` `mdc` ON `mdc`.`username` = 'John'
    LEFT JOIN `movieitemdetails` `md` ON `md`.`barcodes` = '1234567890';