Mysql如何限制左连接结果

时间:2013-11-18 18:40:42

标签: mysql sql limit

我有两张桌子:歌曲和小组

我想限制歌曲与小组匹配到3

我试过这个:

SELECT
groups.`IDgroup`,
groups.`name` AS g_name,
songs.`IDsong`,
songs.`name` AS s_name
FROM  `groups` 
LEFT OUTER JOIN songs ON (groups.`IDgroup` = songs.`IDgroup` LIMIT 3)

5 个答案:

答案 0 :(得分:1)

limit括在括号中:

SELECT
groups.`IDgroup`,
groups.`name` AS g_name,
songs.`IDsong`,
songs.`name` AS s_name
FROM  `groups` 
LEFT OUTER JOIN songs 
ON groups.`IDgroup` = songs.`IDgroup` 
LIMIT 3

答案 1 :(得分:1)

对未明确排序其结果的查询设置限制通常不是一个好主意。原因是随着时间的推移,它可能会返回不同的结果。

因此,您可能需要考虑添加

按组排序。IDgroup,歌曲。IDsong

到您的查询(在LIMIT 3之前),假设这个组合是唯一的。

答案 2 :(得分:1)

SELECT
g.`IDgroup`,
g.`name` AS g_name,
s.`IDsong`,
s.`name` AS s_name
FROM  `groups` g 
LEFT OUTER JOIN songs s 
using ('idgroup')
LIMIT 3

答案 3 :(得分:1)

此查询将返回每组的最后3首歌曲:

SELECT
    c.`IDgroup`,
    c.`name` AS g_name,
    s.`IDsong`,
    s.`name` AS s_name
FROM
    groups c 
        JOIN (
            SELECT 
                IF(@C != c.IDgroup, @ROWNUM := 1, @ROWNUM := @ROWNUM +1) AS RN,
                @C := c.IDgroup,
                c.IDgroup,
                s.IDsong,
                s.name
            FROM groups c 
                LEFT JOIN songs s ON c.`IDgroup` = s.`IDgroup`
                CROSS JOIN (SELECT @C := '') t2
            ORDER BY c.IDgroup ASC
        ) s ON c.`IDgroup` = s.`IDgroup`
        JOIN JOIN (
            SELECT IDgroup, MAX(rn) AS mx
            FROM (
                SELECT 
                    IF(@C != c.IDgroup, @ROWNUM := 1, @ROWNUM := @ROWNUM +1) AS rn,
                    @C := c.IDgroup,
                    c.IDgroup
                FROM groups c 
                    LEFT JOIN songs s ON c.`IDgroup` = s.`IDgroup`
                    CROSS JOIN (SELECT @C := '') t2
                ORDER BY c.IDgroup ASC
            ) t
            GROUP BY IDgroup
        ) maxsong ON maxsong.IDgroup = c.IDgroup AND s.rn BETWEEN maxsong.mx-2 AND maxsong.mx
ORDER BY c.IDgroup ASC, s.`name` ASC

小提琴: http://sqlfiddle.com/#!2/b65c3b/1

答案 4 :(得分:0)

从括号中取出LIMIT:

SELECT
    groups.`IDgroup`,
    groups.`name` AS g_name,
    songs.`IDsong`,
    songs.`name` AS s_name
FROM  `groups` 
LEFT OUTER JOIN songs USING (`IDgroup`)
LIMIT 3