'IF EXISTS ELSE?
How would one fix this query?
IF EXISTS (SELECT * FROM links WHERE age='10')
SELECT * FROM links WHERE age = '10' ORDER BY
ELSE
SELECT * FROM links ORDER BY
So if a link exists which is 10 days exactly then it would be displayed otherwise it would be random.
Solution 1:[1]
You have two different queries - use a union:
SELECT *
FROM links
WHERE age = '10'
UNION ALL
SELECT *
FROM links
WHERE NOT EXISTS (SELECT * FROM links WHERE age='10')
ORDER BT RAND()
Solution 2:[2]
I suppose you could write:
SELECT *
FROM links
WHERE age = '10'
OR NOT EXISTS
( SELECT 1
FROM links
WHERE age = '10'
)
ORDER
BY RAND()
LIMIT 1
;
. . . but I'm not sure how well it will perform. It may make more sense to just run the query with WHERE age = '10'
, and then run the other query only if the first returns no results.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Bohemian |
Solution 2 |