Table who
wid--name-------father---mother
1----Daisy------David----Liza
2----Jenny------Joe------Judy
3----Meggy------Mike-----Manuela
4----Sarah------Joe------Judy
5----Chelsea----Bill-----Hillary
6----Cindy------David----Liza
7----Kelly------Joe------Judy
Table ages
aid---whoid---age
1-----1--------0
2-----2--------0
3-----3-------14
4-----4-------30
5-----5-------22
6-----6-------17
7-----1-------18
I want that list as a result:
id---name------age
1----Meggy-----14
2----Cindy-----17
3----Daisy-----18 (Selected data that bigger than 0)
4----Chelsea---22
5----Sarah-----30
6----Jenny-----30 (Her age is 0 on ages table and Sarah's age with same father and mother)
7----Kelly-----30 (No data on ages table and Sarah's age with same father and mother)
I tried that query:
SELECT
*,
(CASE age
WHEN '0' THEN (
SELECT age
FROM ages a
LEFT JOIN who w
ON w.wid = a.whoid
WHERE
w.father = father
AND
w.mother = mother
ORDER BY a.age DESC LIMIT 1
)
ELSE age
END
) AS newage
FROM who
LEFT JOIN ages
ON wid = whoid
ORDER BY newage
What's wrong with that?
The CASE statement cannot have an ELSE NULL clause, and it is terminated with END CASE instead of END . For the first syntax, case_value is an expression.
ISNULL() Function, COALESCE() Function And CASE Statement There are three ways in which we can remove Null values in Table data and show them to the user. In our Table data, some columns contain null values. We can replace it using ISNULL() function , COALESCE() function, and CASE Statement.
SELECT * FROM yourTableName WHERE yourSpecificColumnName IS NULL OR yourSpecificColumnName = ' '; The IS NULL constraint can be used whenever the column is empty and the symbol ( ' ') is used when there is empty value.
Generally speaking, you can use the CASE expression anywhere that allows a valid expression e.g., SELECT , WHERE and ORDER BY clauses.
CASE … WHEN NULL
will never match anything, and CASE NULL
will always match the ELSE
clause (which in your case returns age
, i. e. NULL
).
Use this:
CASE COALESCE(age, 0) WHEN 0 THEN … ELSE age END
Update:
You also need to alias your tables and use the aliases in the field descriptions:
SELECT *,
CASE COALESCE(age, 0)
WHEN '0' THEN
(
SELECT MAX(age)
FROM who wi
JOIN ages ai
ON ai.whoid = wi.wid
WHERE wi.father = w.father
AND wi.mother = w.mother
)
ELSE
age
END AS newage
FROM who w
LEFT JOIN
ages a
ON a.whoid = w.wid
ORDER BY
newage
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With