2010-03-11 96 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

相关问题