2012-12-22 95 views
2

我有3個表格。MySQL - 查詢語法

news: 
id 
title 

categories:  
id 
name 

newsEachCategories: 
postId 
categoryId 

表newsEachCategories持有每個帖子的ID和它發佈的類別的ID。

因此,如果帖子ID爲13已經發布在類別6和7中,則有兩個條目,一個「postId 13,categoryId 6」和一個「postId 13,categoryId 7」。

所以爲了找到在類別中的所有職位(比如用5號類)我使用:

SELECT news.title , news.editedTitle , news.id 
FROM news JOIN newsEachCategories 
ON news.id = newsEachCategories.postId 
WHERE newsEachCategories.categoryId = 5 

我應該如何synxtax我查詢,如果我要選擇那些兩類職位5和6?

回答

4

要僅返回兩個類別中存在的結果,可以使用COUNT()聚合,並在HAVING子句中驗證返回2個結果。

在這個解決方案中,我加入了一個子查詢,它返回COUNT()每,並限制在這兩個類別中。這是回到主表,以獲得你想要的特定的news.id剩餘的列。

SELECT 
    news.title, 
    news.editedTitle, 
    news.id 
FROM 
    news 
    /* Join against subquery to count occurrences in newsEachCategories */ 
    JOIN (
    SELECT postId, COUNT(DISTINCT categoryId) AS postcount 
    FROM newsEachCategories 
    /* Limit to categories 5 & 6 */ 
    WHERE categoryId IN (5, 6) 
    GROUP BY postId 
    /* Ensures a result was returned for each category 5, 6 */ 
    HAVING postcount = 2 
) postCounts ON news.id = postCounts.postId