简体   繁体   中英

How to apply an ORDER and LIMIT to each sub-query in an IN() clause?

Need to select rows using multiple WHERE params but only return the latest row for each condition; prefer to hit DB with one SQL statement rather than use a loop.

Table

Dummy data:

id  first   last    
------------------------
1   jeff    jones
2   homer   simpson
3   john    doe
4   jeff    jones
5   jeff    jones
6   sam     smith
7   homer   simpson
8   john    doe

SQL

My current sql statement:

SELECT * FROM members
WHERE (first,last) IN (('jeff','jones'), ('homer','simpson')) 
ORDER BY id DESC LIMIT 1

Results needed

Return one row from each sub-query showing the latest entries, ie highest id:

id  first   last    
------------------------
5   jeff    jones
7   homer   simpson

Thanks in advance.

By grouping with first, last you get one result per combination:

SELECT MAX(id), first, last
  FROM members
 WHERE (first,last) IN (('jeff','jones'), ('homer','simpson')) 
 GROUP BY first, last
 ORDER BY id;

MAX(id) selects the maximum id per first / last combination. Order by id afterwards.

Check this Fiddle demo .

ps : added as per comment. Note: you cannot use LIMIT in a sub query. So use a JOIN :

SELECT sup.id, sup.age, sup.first, sup.last 
  FROM members sup
  JOIN ((SELECT id, age, first, last -- choose first two Homers
           FROM members
          WHERE (first,last) IN (('homer','simpson'))
          ORDER BY id DESC 
          LIMIT 2)
          UNION 
        (SELECT id, age, first, last -- unify with first two Jeffs
           FROM members
          WHERE (first,last) IN (('jeff','jones')) 
          ORDER BY id DESC 
          LIMIT 2)) sub              -- left join 
 WHERE sup.id    = sub.id            -- and select only entries from sub
   AND sup.age   = sub.age
   AND sup.first = sub.first
   AND sup.last  = sub.last;

Check this Fiddle here .

Use GROUP BY

SELECT MAX(id), first, last
FROM members
WHERE (first,last) IN (('jeff','jones'), ('homer','simpson')) 
GROUP BY first, last
ORDER BY id DESC
SELECT * 
FROM members m1
WHERE (first,last) IN (('jeff','jones'), ('homer','simpson')) AND 
      id = (SELECT MAX(id) 
            FROM members m2
            WHERE m1.first = m2.first AND m1.last = m2.last)

SQL Fiddle Demo

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