Second SELECT query if first SELECT returns 0 rows

前端 未结 5 1437
萌比男神i
萌比男神i 2020-12-01 16:31

I am trying to speed up a PHP script and I am currently pushing some PHP logic in the Mysql domain of the thing. Is there a way to make a different select query if the first

5条回答
  •  渐次进展
    2020-12-01 17:09

    One option would be to use UNION ALL with EXISTS:

    SELECT * 
    FROM proxies 
    WHERE A='B'
    UNION ALL
    SELECT * 
    FROM proxies 
    WHERE A='C' AND NOT EXISTS (
        SELECT 1
        FROM proxies 
        WHERE A='B'
    )
    
    • SQL Fiddle Demo

    This will return rows from the proxies table where A='B' if they exist. However, if they don't exist, it will look for those rows with A='C'.

提交回复
热议问题