2010-11-28 48 views
0

查詢我有一個相當長的SQL查詢:MySQL的 - 和連接表

SELECT *, content.contentID AS thisID 
FROM content 
LEFT JOIN link_keywords ON content.contentID = link_keywords.contentID 
LEFT JOIN link_countries ON content.contentID = link_countries.contentID 
LEFT JOIN link_sections ON content.contentID = link_sections.contentID 
WHERE status = '1' AND typeID = '1' 
GROUP BY contentID 
ORDER BY creationDate DESC 

我回去一組結果,我想這樣做是顯示所有的結果,其中sectionID(這是從link_sections加入)等於3或4.換句話說,在第3部分和第4部分中的所有結果。

以下查詢不返回任何東西,大概是因爲它檢查單個排sectionID等於3和4.我需要的是任何content.contentIDsectionID等於3和4.

SELECT *, content.contentID AS thisID 
FROM content 
LEFT JOIN link_keywords ON content.contentID = link_keywords.contentID 
LEFT JOIN link_countries ON content.contentID = link_countries.contentID 
LEFT JOIN link_sections ON content.contentID = link_sections.contentID 
WHERE status = '1' AND typeID = '1' AND (sectionID = '3' AND sectionID = '4') 
GROUP BY contentID 
ORDER BY creationDate DESC 
+1

*我需要的是任何content.contentID與sectionID等於3和4 *那是不可能的。你的意思是*兩行*具有相同的content.contentID並且sectionID分別等於3和4? – 2010-11-28 20:52:24

+0

嗨。是的,所以想象content.contentID等於1(這是一篇文章記錄)。本文可以在許多不同的部分。因此,我只想要第3部分和第4部分中的文章記錄。 – Chris 2010-11-28 20:54:56

+0

您可以發佈您的模式嗎? – 2010-11-28 20:58:53

回答

2

你可以使用子查詢:

SELECT *, content.contentID AS thisID 
FROM content 
LEFT JOIN link_keywords ON content.contentID = link_keywords.contentID 
LEFT JOIN link_countries ON content.contentID = link_countries.contentID 
LEFT JOIN link_sections ON content.contentID = link_sections.contentID 
WHERE status = '1' AND typeID = '1' AND 
     content.contentID IN (SELECT section3.contentID 
          FROM link_sections AS section3 
          WHERE sectionID = 3) AND 
     content.contentID IN (SELECT section4.contentID 
          FROM link_sections AS section4 
          WHERE sectionID = 4) 
GROUP BY contentID 
ORDER BY creationDate DESC 
1

試試這個:

SELECT 
    *, 
    content.contentID AS thisID 
FROM content 
    LEFT JOIN link_keywords 
    ON content.contentID = link_keywords.contentID 
    LEFT JOIN link_countries 
    ON content.contentID = link_countries.contentID 
    LEFT JOIN link_sections 
    ON content.contentID = link_sections.contentID 
WHERE 
(SELECT COUNT(contentID) AS counter FROM link_sections s2 WHERE s2.contentID=content.contentID AND (sectionID='3' OR sectionID='4') GROUP BY contentID)=2 
    AND STATUS = '1' 
    AND typeID = '1' 
    AND (sectionID = '3' 
     OR sectionID = '4') 
GROUP BY content.contentID 
ORDER BY creationDate DESC; 
0

你需要做的是sectionID = '3' 選擇行與sectionID = '4' 與相交行的結果。