使用LIMIT和JOIN

时间:2013-01-22 17:56:35

标签: mysql

我有两张桌子:乐队和专辑。这是结构

波段: id_band 名称

相册 id_album id_band 名称

所以,我需要一个查询来显示来自持续插入乐队的所有专辑。

我试试这个:

SELECT bands.name, albums.name
FROM bands
JOIN albums ON albums.id_band = bands.id_band
ORDER BY bands.id_band DESC
LIMIT 1

但我只收到第一张专辑。并非所有专辑来自持续插入的乐队。我该如何解决?

2 个答案:

答案 0 :(得分:2)

SELECT b.name, a.name
FROM (SELECT name, id_band
    FROM bands
    ORDER BY id_band DESC
    LIMIT 1) AS b
JOIN albums a ON a.id_band = b.id_band 

答案 1 :(得分:0)

查询:

SELECT b.name,
       a.name
FROM bands b
JOIN albums a ON a.id_band = b.id_band
WHERE b.id_band = (SELECT max(id_band)
                   FROM bands)