开发者

Selecting record from two tables with INNER join limit 3

I have records in two tables as shown below

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        1开发者_JAVA百科5789
9        4557
9        7667
9        1556
9        4556
9        764

Now I want the first 3 records from table1 with userid in descending order along with the table2 records related to them


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


    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


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

Explanation:
Group_concat is an aggregate function that will make a list of comma separated values.
Because you are using an aggregate function you need to group on userid.
The limit 3 selects the first 3 userid's (because you've ordered ASC)
Then the outer select picks up all 3 rows and reverses the order to DESC.

Links
http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜