2010-03-11 32 views
1

我試圖查詢一組列表中的列表,這些建築物與標籤鏈接。我能夠做到這一點,但我的問題是如何限制的標籤的數量看:爲每個選擇一個元素和5個標籤的列表

table buildings 
id building_name  style 
1  Pompidou   bla 
2  Alcatraz   bla 
3  etc.    etc. 

table tags // they can be 50 or more per building 
id tag_name 
1  minimal 
2  gothic 
3  classical 
4  modern 
5  etc. 

table buildings_tags 
id building_id  tag_id 

我雖然做這樣的事情來檢索列表,但這不是compplete:

SELECT DISTINCT(tag), bulding_name 
FROM buldings 
INNER JOIN buildings_tags 
ON buildings.id = buildings_tags.building_id 
INNER JOIN tags 
ON tags.id = buildings_tags.tag_id 
LIMIT 0, 20 

// result 

building  tag 
Pompidou  great 
Pompidou  france 
Pompidou  paris 
Pompidou  industrial 
Pompidou  renzo piano  <= How to stop at the 5th result? 
Pompidou  hi-tech 
Pompidou  famous place 
Pompidou  wtf 
etc..  etc... 

此查詢加載建築物,但是此查詢加載爲建築物鏈接的所有標記,而不僅僅是其中的5個?

+0

你有沒有嘗試任何疑問? – Patrick 2010-03-12 18:07:26

+0

還沒有,我會盡快做,謝謝你的幫助! – vitto 2010-03-13 10:35:11

回答

2

在我看來,你所要求的與你的查詢所做的不同。如果我理解你的權利,這個查詢應該做你需要的東西:

SELECT bulding_name, tag 
FROM buldings b 
    LEFT JOIN (SELECT tag, building_id 
       FROM tags 
       INNER JOIN buildings_tags 
        ON tags.id = buildings_tags.tag_id 
       WHERE building_id = b.id 
       LIMIT 5) t 
    ON b.id = t.building_id 
ORDER BY bulding_name 

這將讓你所有的建築物,至多5個標籤爲每個。儘管如此,可能還有一種更優雅的方式。

0

如果我理解你的想法,你應該改變:

LIMIT 0,20 

由:

LIMIT 0,5 

或者只是:

LIMIT 5 

這一切!

0
SELECT a.building_name, a.tag_name 
FROM (
SELECT b.building_name, t.tag_name, bt.building_id 
FROM tags t 
    INNER JOIN buildings_tags bt ON (bt.tag_id=t.id) 
    INNER JOIN buildings b ON (b.id=bt.building_id) 
ORDER BY bt.building_id 
) a 
, 
(SELECT @prev:=-1, @count:=1) b 
WHERE 
CASE WHEN @prev<>a.building_id THEN 
    CASE WHEN @prev:=a.building_id THEN 
    @count:=1 
    END 
ELSE 
    @count:[email protected]+1 
END <= 5 

如果這場比賽你的需求,然後解釋近似相同的查詢here

相關問題