Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.0k views
in Technique[技术] by (71.8m points)

mysql - Second SELECT query if first SELECT returns 0 rows

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 Select returns no rows, or a count of zero ?

Keeping in mind that the first query needs to run first, and the second should only be activated if the first one returns an empty set.

SELECT * FROM proxies WHERE (A='B') || SELECT * FROM proxies WHERE (A='C')

For the above 2 queries I have this code, but it seems to run each query twice (once to count, and once to return). Is there a better way to do this?

IF (SELECT count(*) FROM proxies WHERE A='B')>0
    THEN SELECT * FROM proxies WHERE A='B'
ELSEIF (SELECT count(*) FROM proxies WHERE A='C')>0
    THEN SELECT * FROM proxies WHERE A='C'
END IF
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...