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 *
FROM proxies
WHERE A=(CASE WHEN
(SELECT COUNT(*) FROM proxies WHERE A='B') > 0 THEN'B'
ELSE 'C' END)
UPDATE
SELECT *
FROM proxies
WHERE (
CASE WHEN (SELECT COUNT(*) FROM proxies WHERE A='B' LIMIT 1) > 0 THEN
(A='B')
WHEN (SELECT COUNT(*) FROM proxies WHERE A='C' LIMIT 1) > 0 THEN
(A='C')
WHEN (SELECT COUNT(*) FROM proxies WHERE A='D' LIMIT 1) > 0 THEN
(A='D')
ELSE 1=2 END)
I think this more or less covers what you're trying to do. If you need the count of rows returned just get the value from mysqli->num_rows
$db = new mySQLi(etc);
//run your first query
$query = "SELECT * FROM proxies WHERE A='B'";
$result = $db->query($query);
//check for rows returned
if($result->num_rows > 0){
//if there are rows get them
while($row = $result->fetch_assoc()){
//deal with the results
}
} else {
//otherwise run your other query and get those results
$query = "SELECT * FROM proxies WHERE A='C'";
$result = $db->query($query);
while($row = $result->fetch_assoc()){
//deal with the results
}
}
Another way:
SELECT A INTO @v FROM proxies ORDER BY A LIMIT 1;
SELECT * FROM proxies WHERE A=@v
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'
.
In a general case where you have multiple values for A
(lets say, 'B', 'C', 'D', 'E', etc.) and you want to retrieve only the rows that belong to the lowest value that exists, then you would use the following query. This will work also for the particular case you exposed.
SELECT p1.*
FROM proxies p1
LEFT JOIN proxies p2
ON p1.A > p2.A
WHERE p2.A IS NULL
Fiddle