I have this mysql statement but I receive LIMIT in subquery error
SELECT id
FROM articles
WHERE section=1 AND id NOT IN
(
SELECT id
FROM articles
WHERE is_top_story=1 ORDER BY timestamp DESC LIMIT 2
)
I want to select all id-s from table where section=1 and id-s not in my inner(second) statement
+--id--+section+-is_top_story-+--timestamp--+
| 54 | 1 | 1 | 130 |
| 70 | 2 | 0 | 129 |
| 98 | 3 | 1 | 128 |
| 14 | 1 | 1 | 127 |
| 58 | 4 | 0 | 126 |
| 13 | 3 | 1 | 125 |
| 64 | 1 | 1 | 124 |
| 33 | 1 | 1 | 123 |
My sql should return 64 and 33(they are with section=1 and is_top_story=1), because 54 and 14 (are in inner statment)
If any can give me some code I will be very grateful
Thanks
How about this:
Join is a usual workaround when you need limits in subqueries; need for excluding logic just adds these ‘left join – joined.id IS NULL` parts to query. )
UPDATE: Got a bit confused by your example. The original query you’ve quoted was “take some articles with section = 1, then take out those that belong to the 2 most recent top_stories”. But in your example the section should also be taken into account when selecting these stories-to-ignore-…
It’s actually quite easy to update my query with that condition as well: just replace
with
… but I think it might be even better solved at the client code. First, you send a simple query, without any joins whatsoever:
Then you just walk through the fetched rowset, and just ignore two first elements with ‘is_top_story’ flag on, like that: