在我的项目中,我有3个mysql查询,一个用于获取公司下一个事件的信息,一个用于上一个事件的信息,我想为所有其他事件制作一个。
日期由下式给出: $日期=日期( “Y-M-d”);
我有下一个活动: SELECT * FROM passeio WHERE passeio_date> $ date LIMIT 0,1
对于之前的活动,我有: SELECT * FROM passeio WHERE passeio_date< $ date LIMIT 0,1
如何获取除上一个和下一个事件之外的所有其他行。
提前致谢!
答案 0 :(得分:0)
如果您在表上有主键,则可以查询上述两个查询的组合以获取所有“其他”行:
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
)
答案 1 :(得分:0)
使用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
,因为您不需要消除重复项。
或许更有效的方法是:
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。