2009-12-03 122 views
0

我擁有包含列表,類別和映射它們的表格。因此,列表可以放在多個類別中。像下面這樣:MySQL爲多個條件返回不同的結果

listings table 
    id 
    title 
    etc 

categories table 
    id 
    category_name 
    etc 

map table 
    listing_id 
    category_id 

當我需要把所有的信息在單個類別中的列表(在這種情況下,與18的ID的類),以下工作正常:

SELECT * 
FROM (`listings`, `map`) 
WHERE `map`.`category_id` = 18 
AND map.listing_id = listings.id 

我的問題是我如何做類似的查詢類型,但現在我需要找到兩個類別內的不同列表。例如,如果我只需要返回category_id = 18和category_id = 20中的不同列表,那該怎麼辦?這是否需要某種類型的連接?

+0

你想排除你的結果的列表設置,如果它是在更不僅僅是你指定的兩個類別? – 2009-12-03 18:38:03

回答

2

是的,你會想要使用(另一個)加入。我認爲有以下應該這樣做:

SELECT lst.`id`, lst.<column>, ... 
FROM `listings` lst, `map` m, `map` m2 
WHERE m.`category_id` = 18 AND m2.`category_id` = 20 
AND m.`listing_id` = lst.`id` 
AND m2.`listing_id` = lst.`id` 

另一個版本,由生殖的建議的啓發,但是這一個工程(注意我換成idcategory_id爲清楚起見):

select l.listing_id 
from listings l 
join (select m.listing_id, count(*) as cnt from map m where 
    m.category_id in (18,20) 
    group by m.listing_id) cat_matches 
    on cat_matches.listing_id = l.listing_id 
where cat_matches.cnt = 2; -- 2 is the number of distinct categories to match 

醜女誒?和子選擇可能不是所有有效的...但:


select l.listing_id 
from listings l 
join map m on l.listing_id=m.listing_id 
where m.category_id in (18,20) 
group by l.listing_id 
having COUNT(*)=2; 

你可以得到你所需要的所有行,然後篩選它們消除子查詢中。請注意,此解決方案假定映射表中的行是唯一的(應該是這種情況,因爲PK應在listing_idcategory_id之間定義)。

+0

非常感謝,完美工作 – Frank 2009-12-03 18:51:12

+1

每次需要使用此方法的其他類別時,您都需要繼續加入地圖表 – Germ 2009-12-03 19:11:31

+0

同意,Germ的解決方案可能是針對此問題的更好解決方案。 – 2009-12-03 19:13:43

1

這應該工作

select * from listings l 
join map m on m.listing_id = l.id 
join categories c on c.id = m.category_id 
where c.id in (18, 20) 
+0

正確加入+1! – 2009-12-03 18:40:17

+0

@pcampbell:SQL99 JOINs更準確 – 2009-12-03 18:44:50

+0

感謝您的幫助,我在解決此問題方面遇到了一些問題。 – Frank 2009-12-03 18:54:48

0

這個怎麼樣...

​​

select * from listings l, map m, categories c 
where l.id = m.listing_id 
and m.category_id = c.id 
and c.id in (18, 20) 
+0

這甚至不會運行,在單個查詢中不能有兩個'WHERE'子句。 – 2009-12-03 21:28:11

+0

你明白了:)固定 – Germ 2009-12-03 22:47:54

相關問題