在mysql中连接两个表时对一个表使用限制

时间:2014-08-21 08:55:46

标签: mysql sql

在这种情况下,如何使用限制和连接正确编写sql语句?

SELECT  u.userName, u.userFriends, u.userJoined, f.freindName (only 3) 
FROM    user u inner join friends f ON u.userId = f.addedUserId 
WHERE   u.userId=1 
AND     f.userId=1

我试过

SELECT  u.userName, u.userFriends, u.userJoined, group_concat(f.freindName) 
FROM    user u inner join friends f ON u.userId = f.userId 
WHERE   u.userId = 1 and f.addedUserId = 1 
GROUP   by u.userName limit 5 /* but this does not work */

您能否帮助限制f.freindName to 3

'gid'  | 'userName'  | 'userId' |   'userFriends'   |'userJoined'
-------|-------------|----------|-------------------|--------------
'1'    | 'Jason'     | '1'      |   '5'             |'14-Aug-2014'


'gid'  | 'friendName'|  'thisUserId'    |'addedUserId'
-------|-------------|------------------|-----------------
'1'    | 'James'     |  '2'             |'1'
'2'    | 'Lars'      |  '3'             |'1'
'3'    | 'Kirk'      |  '4'             |'1'
'4'    | 'Rob'       |  '5'             |'1'
'5'    | 'Dave'      |  '5'             |'1'

2 个答案:

答案 0 :(得分:2)

我假设用户和朋友的表由userId和addedUserId列连接在一起。我进一步假设你想要一个拥有userId = 1的用户的三个朋友的列表。

您可以使用子选择来使用派生表来获得所需的结果:

SELECT  u.userName, u.userFriends, u.userJoined, group_concat(f.friendName) 
FROM    user u 
INNER JOIN (
    SELECT
        userId,
        friendName
    FROM
        friends
    LIMIT 3
) f
ON u.userId = f.addedUserId 
WHERE   u.userId = 1
GROUP   by u.userName

应该有用。

答案 1 :(得分:0)

这是您要查找的查询。我认为字段名称存在一些问题(例如f.freindName而不是f.friendname),但要解决这个问题,这应该有效

SELECT  u.userName, u.userFriends, u.userJoined, f.freindName 
FROM    user u inner join friends f ON u.userId = f.userId 
   (SELECT  DISTINCT f.freindName 
    FROM    user u2 inner join friends f2 ON u2.userId = f2.userId
    WHERE u2.userId = u.userId
    LIMIT 3) as f
WHERE   u.userId=1