简体   繁体   中英

How do I combine MySQL statements with an “IF”?

How do I combine these into one statement using 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

Here's one way to get the list:

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

It's the end of a looong day so I hope I got the count zero/nonzero logic straight :)

BTW, I agree with @Max that the downvote was undeserved. I voted the question up.

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

One option is:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM