说我有一个歌曲数据库。
ARTIST | SONG
-------------------------------------
Cloud Cult The Meaning of 8
Cloud Cult Pretty Voice
Jason Alexander Today Was a Good Day
Jason Alexander Like a Virgin
Jason Alexander It Wasn't Me
Powderfinger Like a Dog
我想要做的是发出一个查询,选择限制为20位艺术家的所有歌曲。不仅仅有20个数据库记录,还有20位艺术家的歌曲。所以在上面的例子中,如果我限制为2,我将获得5个结果,所有歌曲都由Cloud Cult和Jason Alexander的所有歌曲。
这是SQL可以做的吗?
答案 0 :(得分:2)
您需要根据所需艺术家的数量创建艺术家的子查询和LIMIT
子查询:
MySQL 5.5.32架构设置:
CREATE TABLE Table1
(`ARTIST` varchar(15), `SONG` varchar(20))
;
INSERT INTO Table1
(`ARTIST`, `SONG`)
VALUES
('Cloud Cult', 'The Meaning of 8'),
('Cloud Cult', 'Pretty Voice'),
('Jason Alexander', 'Today Was a Good Day'),
('Jason Alexander', 'Like a Virgin'),
('Jason Alexander', 'It Wasn''t Me'),
('Powderfinger', 'Like a Dog')
;
查询1 :
select t.*
from (select distinct ARTIST from table1 LIMIT 2) a
INNER JOIN table1 t on a.ARTIST = t.ARTIST
<强> Results 强>:
| ARTIST | SONG |
|-----------------|----------------------|
| Cloud Cult | The Meaning of 8 |
| Cloud Cult | Pretty Voice |
| Jason Alexander | Today Was a Good Day |
| Jason Alexander | Like a Virgin |
| Jason Alexander | It Wasn't Me |
答案 1 :(得分:2)
Select * FROM LibraryTable lt
WHERE lt.artist IN (SELECT
DISTINCT lt2.artist
FROM LibraryTable lt2 LIMIT ***X***)
X 是您的艺术家限制。
答案 2 :(得分:0)
您可以使用group by function选择特定数据,这是代码
select table1.artist, table1.song from
(select artist from table1
group by artist limit 2) t1
inner join table1 on t1.artist=table1.artist