MySQL - 对连接表的AND查询

时间:2010-11-28 20:48:53

标签: mysql join

我有一个很长的SQL查询:

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.contentID sectionID等于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

3 个答案:

答案 0 :(得分:2)

您可以使用子SELECT:

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 :(得分: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;

答案 2 :(得分:0)

您需要做的是选择sectionID ='3'的行,并将结果与​​sectionID ='4'的行相交。