0

在我的项目中,我有 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

除了上一个和下一个事件之外,我该如何获取所有其他行。

提前致谢!

4

2 回答 2

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
)
于 2013-03-29T16:10:48.027 回答
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
)

I also switched the union to a union all because you do not need to eliminate duplicates.

Perhaps a more efficient way to do this is:

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

Whether this is more or less efficient depends on the data structure, but it eliminates the anti-join and doesn't require having an ID.

于 2013-03-29T22:25:03.277 回答