表格:
|A | |B | |C |
|-----| |-----|-----| |-----|-----|-----------|--------|
|AKey | |BKey |AKey | |CKey |BKey |Date |Result |
|-----| |-----|-----| |-----|-----|-----------|--------|
|1 | |1 |1 | |101 |1 |2016-12-01 |F |
| | |2 |1 | |102 |1 |2016-12-01 |F |
| | |3 |1 | |103 |3 |2016-12-01 |P |
| | | | | |104 |1 |2016-12-01 |P |
我试过这个SQL命令:
SELECT a.Akey, b.BKey, c.CKey, Date, Result
FROM A AS a
INNER JOIN B as b ON a.AKey=b.AKey
LEFT JOIN (SELECT * FROM C WHERE Date="2016-12-01"
ORDER BY CKey DESC
LIMIT 0, 1) AS c ON c.BKey=b.BKey
WHERE a.AKey=1
我得到的结果如下:
|AKey |BKey |CKey |Date |Result |
|-----|-----|-----|-----------|--------|
|1 |1 |104 |2016-12-01 |P |
|1 |2 |NULL |NULL |NULL |
|1 |3 |NULL |NULL |NULL |
但是,如何得到如下结果?
|AKey |BKey |CKey |Date |Result |
|-----|-----|-----|-----------|--------|
|1 |1 |101 |2016-12-01 |P |
|1 |2 |NULL |NULL |NULL |
|1 |3 |103 |2016-12-01 |P |
答案 0 :(得分:1)
你可能想要这样的东西:
GROUP BY
您必须使用CKey
子句才能获得每BKey
的最小C
值。然后加入{{1}}表格以获得更多其他字段。
答案 1 :(得分:1)
您的内部查询始终选择相同的行。您可以使用Akey
NOT EXISTS()
的最新记录
SELECT a.Akey, b.BKey, c.CKey, Date, Result
FROM A AS a
INNER JOIN B as b ON a.AKey=b.AKey
LEFT JOIN (SELECT *
FROM C
WHERE Date="2016-12-01"
AND NOT EXISTS(SELECT 1 FROM c t1
WHERE t1.cid > c.cid
and t1.bkey = c.bkey) ) AS c
ON c.BKey=b.BKey
WHERE a.AKey=1