我在MySql中有一个表,我保存了一些数据,让我们假设一个名字和一个立场.
我知道看台将从1到100,我想选择那些未被占用的看台.例如,让我们假设只有5个看台和这个表:
| name | stand | -------------------- | test | 1 | | anot | 3 | | blah | 4 | | uuuh | 5 |
@H_301_9@在这种情况下,唯一的免费展位将是2.
最佳答案
如果您知道值为1到100,那么您可以这样做:
select n.num from (select d1.d*10 + d2.d as n from (select 0 as d union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9 ) d1 cross join (select 0 as d union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9 ) d2 ) nums left outer join stands s on s.stand = nums.n cross join (select min(stand) as minstand and max(stand) as maxstand from stands) const where s.stand is null and nums.n between minstand and maxstand;
@H_301_9@这未经过测试,因此可能存在语法错误.
也就是说,创建一个包含所有可能值(1到100)的表.左边加入你的桌子.这将为您提供未使用的所有数字.但是,您希望将其限制为最小值和最大值,因此请计算这些值并将其用于过滤器.