如何将ORDER和LIMIT应用于IN()子句中的每个子查询?

时间:2015-05-08 18:52:22

标签: mysql

需要使用多个WHERE参数选择行,但只返回每个条件的最新行;我喜欢用一个SQL语句命中DB,而不是使用循环。

表格

虚拟数据:

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

我当前的sql语句:

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

需要的结果

从显示最新条目的每个子查询中返回一行,即最高ID:

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

提前致谢。

3 个答案:

答案 0 :(得分:1)

通过使用SELECT MAX(id), first, last FROM members WHERE (first,last) IN (('jeff','jones'), ('homer','simpson')) GROUP BY first, last ORDER BY id; 分组,您可以获得每个组合一个结果:

MAX(id)

id选择每first / lastid组合。之后按LIMIT排序。

选中Fiddle demo

p.s。 :根据评论添加。注意:您不能在子查询中使用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;

var slotsDiv  = $('.fc-slats:visible');

选中Fiddle here

答案 1 :(得分:0)

使用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

答案 2 :(得分:0)

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