选择带连接的查询

时间:2015-10-30 09:40:44

标签: oracle select join

我有桌子:

diagram of tables

如何选择具有特定TAGS的NEWS,例如使用两个TAGS?

这是我错误的变种:

SELECT DISTINCT news.news_id, news.CREATION_DATE, news.MODIFICATION_DATE, news.FULL_TEXT, news.TITLE, news.SHORT_TEXT
    FROM
      news
      INNER JOIN
      news_tags
        ON news.news_id = news_tags.news_id
        WHERE news_tags.TAG_ID = 1 AND news_tags.TAG_ID = 3;

2 个答案:

答案 0 :(得分:0)

SELECT DISTINCT news.news_id, news.CREATION_DATE, news.MODIFICATION_DATE, news.FULL_TEXT, news.TITLE, news.SHORT_TEXT
FROM
  news
  INNER JOIN
  news_tags
    ON news.news_id = news_tags.news_id
       inner join Tags on Tags.Tag_Id = news_tags.Tag_Id
    WHERE news_tags.TAG_ID = 1 AND news_tags.TAG_ID = 3;

答案 1 :(得分:0)

如果您想获得带有标签1和3的新闻,您应该检查news_tags表中是否存在带有tag_id 1的记录和带有tag_id 3的记录。现在你要求标签为1且同时为3的新闻,这并不是真的有意义。

这样的事情:

SELECT DISTINCT news.news_id, news.CREATION_DATE, news.MODIFICATION_DATE, news.FULL_TEXT, news.TITLE, news.SHORT_TEXT
FROM news INNER JOIN news_tags ON news.news_id = news_tags.news_id
WHERE EXISTS (SELECT 1
              FROM news_tags
              WHERE news_id = news.news_id
              AND tag_id = 1)
AND EXISTS (SELECT 1
            FROM news_tags
            WHERE news_id = news.news_id
            AND tag_id = 3);