【发布时间】:2011-06-07 05:51:04
【问题描述】:
表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
表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
我想要那个列表作为结果:
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)
我试过那个查询:
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
这有什么问题?
【问题讨论】:
-
子选择中的父亲和母亲可能与外部查询中的父亲和母亲混淆了。还是您在问为什么它不是最佳的?
-
是的,它与父亲和母亲完全混淆。子查询是从年龄表中选择最大的年龄,而不是“同父同母”。我只是想选择我写的列表,无所谓,它是否是最优的。
标签: mysql select sql-order-by case