2014-11-05 39 views
2

說我有一個歌曲的數據庫。我可以通過特定列的唯一計數來限制嗎?

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可以做的事嗎?

回答

2

您需要創建藝術家的子查詢和LIMIT所要求的藝術家的數子查詢:

SQL Fiddle

MySQL的32年5月5日架構設置

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 | 
2
Select * FROM LibraryTable lt 
WHERE lt.artist IN (SELECT 
        DISTINCT lt2.artist 
        FROM LibraryTable lt2 LIMIT ***X***) 

X是你的藝術家的限制。

0

您可以使用組由功能來選擇具體的數據,這裏是代碼

select table1.artist, table1.song from 
(select artist from table1 
    group by artist limit 2) t1 
inner join table1 on t1.artist=table1.artist 
相關問題