This question is directed specifically toward MySQL, but I'm trying to ask it in such a way that standard SQL is applicable.
Context: I am trying to determine an end date in the following way: if there exists another start date after the entered start date, use the existing start date as the end date; otherwise, the end date should be 30 days after the entered start date.
The solution I've tried is similar to the following:
SELECT
IF(
EXISTS(
SELECT
DISTINCT start_date
FROM table
WHERE ? < start_date AND
identifier = ?
ORDER BY start_date
LIMIT 1
), (
SELECT
DISTINCT start_date
FROM table
WHERE ? < start_date AND
identifier = ?
ORDER BY start_date
LIMIT 1),
DATE_ADD(?, INTERVAL 30 DAY)
) AS end_date
My solution works, but I was hoping there were a more elegant, non-repetitive solution.
The generic solution would be one which—if a subquery exists—returns the values from the subquery; otherwise, something else can be returned.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…