考虑这个小样本数据集:
| id | territory_id | signed_in
| 1 | 6 | 2010-12-22 01:00:00
| 2 | 6 | 2011-12-11 01:00:00
| 3 | 6 | 2013-03-13 01:00:00
| 4 | 6 | NULL
| 5 | 3 | 2013-03-06 01:00:00
| 6 | 3 | 2013-11-20 01:00:00
我希望将结果按territory_id
分组,其中整个组不包含signed_in
为NULL
的行。或者基本上我想得到这些结果:
| 5 | 3 | 2013-03-06 01:00:00
| 6 | 3 | 2013-11-20 01:00:00
这是我当前的sql,它在加入signed_in
表时查找每个组的最大territories
值:
SELECT `territories`.`id`, `territories`.`label`, `territories`.`type_id`, `territories`.`area_type_id`, `territories`.`map_embed_id`, `tsio`.`signed_in`
FROM `territories` INNER JOIN (
SELECT territory_id, MAX(signed_in) signed_in
FROM `territories_sign_in_out`
GROUP BY territory_id) tsio ON `territories`.`id` = `tsio`.`territory_id`
WHERE `territories`.`type_id` = ?
ORDER BY `tsio`.`signed_in` ASC
LIMIT 15
答案 0 :(得分:1)
试试这个:
select * from territories
where territory_id not in (
select territory_id from territories where signed_in is null);
答案 1 :(得分:0)
这是一个应该返回您正在寻找的结果的查询:
SELECT *
FROM territories T
LEFT OUTER JOIN (SELECT DISTINCT T2.territory_id
FROM territories T2
WHERE T2.signed_in IS NULL) TN ON TN.territory_id = T.territory_id
WHERE TN.territory_id IS NULL
希望这会对你有所帮助。