[英]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.