简体   繁体   中英

Mysql Query to get all rows from table except 2

In my project i have 3 mysql queries, one for get the info for the next event of the company, one for the info for the previous event and i want to make one for all other events.

The date is given by: $date=date("Ymd");

For the next event i have: SELECT * FROM passeio WHERE passeio_date > $date LIMIT 0,1

For the previous event i have: SELECT * FROM passeio WHERE passeio_date < $date LIMIT 0,1

How can i do to get all others rows except the previous and the next event.

Thanks in advance!

If you have a primary key on the table, you can query a combination of above two queries to get all 'other' rows:

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
)

When using limit , you should always include an order by if you have a specific ordering in mind. I think the query you want is:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM