[英]Mysql Query to get all rows from table except 2
在我的项目中,我有3个mysql查询,一个用于获取公司下一个事件的信息,一个用于上一个事件的信息,而我想为所有其他事件做一个。
日期通过以下方式给出:$ date = date(“ Ymd”);
对于下一个事件,我有:SELECT * FROM passeio WHERE passeio_date> $ date LIMIT 0,1
对于上一个事件,我有:SELECT * FROM passeio WHERE passeio_date <$ date LIMIT 0,1
我如何获取除上一个和下一个事件以外的所有其他行。
提前致谢!
如果表上有主键,则可以查询上述两个查询的组合以获取所有“其他”行:
select * from passeio where ID not in
( select * from (
select ID from passeio where passeio_date > $date LIMIT 0,1
UNION
select ID from passeio where passeio_date < $date LIMIT 0,1
)t
)
使用limit
,如果您有特定的顺序,则应始终包含一个order by
。 我认为您想要的查询是:
select * from passeio where ID not in
( select * from (
select ID from passeio where passeio_date > $date order by passeio_date asc LIMIT 1
UNION ALL
select ID from passeio where passeio_date < $date order by passeio_date desc LIMIT 1
)t
)
我还将union
改为union all
union
,因为您不需要消除重复。
也许更有效的方法是:
select *
from passeio
where passeio_date > $date
order by passeio_date
limit 1, 1000000000
union all
select *
from passeio
where passeio_date < $date
order by passeio_date desc
limit 1, 1000000000
效率的高低取决于数据结构,但是它消除了反联接,并且不需要具有ID。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.