我有如下的dB表
id | branch | allot
1 | Comp | -1
2 | IT | -1
3 | Comp | -1
1 | Comp | 1
其中allot=-1
表示已分配座位,allot=1
表示已取消座位
我想要一个只返回id = 2,3的MySQL查询 不是id = 1,因为它稍后取消了座位。
答案 0 :(得分:0)
您的问题具体说明"稍后"。这不能用您的数据格式完成,因为SQL表表示无序集。并且,您没有指定排序的列。
如果您希望获得-1
值并排除1
值,则有多种方法。一种是使用not exists
:
select t.*
from dbtable t
where allot = -1 and
not exists (select 1
from dbtable t2
where t2.id = t.id and t2.allot = 1
);
如果您稍后发现了一个确实有记录顺序的列(例如createdat
),那么您可以轻松地将其修改为:
select t.*
from dbtable t
where allot = -1 and
not exists (select 1
from dbtable t2
where t2.id = t.id and t2.allot = 1 and
t2.createdat > t.createdat
);
答案 1 :(得分:0)
heroku config -s | grep HEROKU_POSTGRESQL
这样,当同一个座位存在2行时,选择SELECT `id`, `branch`, MAX(`allot`)
FROM `table`
GROUP BY `id`
WHERE `allot` = -1
= 1的那一行(自MAX起),然后最终从选择中删除(从WHERE开始)。