同一个表

时间:2015-10-26 01:22:33

标签: mysql sql subquery

尝试获取userid ='me'

的所有行

然后是2个最新的行,其中userid<> '我'

产品:

Userid time
other2   11
other3   10
me       10
me        8
other1    8
other3    7
me        6

将返回

Userid  time
me        10
me         8
me         6
other2    11
other3    10

结果不一定是

(SELECT * FROM Items WHERE userid='me' )
UNION ALL
(SELECT * FROM Items  WHERE userid<>'me' 
ORDER BY time DESC  LIMIT 2)

这只输出2行

1 个答案:

答案 0 :(得分:2)

sql是正确的,如上所示

(SELECT * FROM Items WHERE userid='me' )
UNION ALL
(SELECT * FROM Items  WHERE userid<>'me' 
ORDER BY time DESC  LIMIT 2)

Union All连接两个查询,括号允许不同的WHERE / ORDER BY / LIMIT子句。
在这里展示: http://sqlfiddle.com/#!9/ca405/1/0