从具有INNER连接限制3的两个表中选择记录

时间:2011-08-04 06:32:47

标签: mysql join

我在两个表中有记录,如下所示

Table1
userid    email
1        123@qwe.com
4        qwe@sdf.cok
5        sad@fgdf.sdf
7        dsvh@dsf.we
9        fdsdf@fgh.hh

Table 2
userid    values
1        15
1        45
1        76
1        15345
4        4545
4        76788
4        15879
5        4534
5        76345
5        15678
5        4567
5        7667789
7        15
7        456786
7        76678
7        15678
9        45789
9        76789
9        15789
9        4557
9        7667
9        1556
9        4556
9        764

现在我希望table1的前3条记录与userid一起降序以及与它们相关的table2条记录

3 个答案:

答案 0 :(得分:0)

    SELECT a.userid, a.email, b.values 
    FROM table1 a
    INNER JOIN table2 b ON a.userid = b.userid
    ORDER BY a.userid asc
    LIMIT 0,3

答案 1 :(得分:0)

SELECT *
FROM (SELECT TOP 3 * FROM Table1) AS Table1 INNER JOIN
     Table2 ON Table1.userid = Table2.userid
ORDER BY Table1.userid

答案 2 :(得分:0)

SELECT * FROM (
  SELECT t1.userid, t1.email, group_concat(t2.`values`) as t2values
  FROM table1 t1
  INNER JOIN table2 t2 ON (t1.userid = t2.userid)
  GROUP BY t1.userid
  ORDER BY t1.userid ASC
  LIMIT 3 ) subselect
ORDER BY subselect.userid DESC

<强>解释
Group_concat是一个聚合函数,它将列出逗号分隔值 因为您正在使用聚合函数,所以需要对userid进行分组 limit 3选择前3个用户ID(因为您订购了ASC)
然后外部选择拾取所有3行并将顺序反转为DESC。

<强>链接
http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat