选择多个匹配映射表的项目一次

时间:2012-02-22 19:17:21

标签: mysql join

我正在尝试选择具有特定主题ID的问题。这些匹配存储在映射表中,但我无法弄清楚如何选择有两个标记的问题,因为它们存储在表中的不同行中!有什么帮助吗?

SELECT questions. * , posts.post, posts.id AS post_id, posts.created, users.id AS user_id, users.username, users.rep
FROM questions
LEFT JOIN posts ON questions.id = posts.question_id
LEFT JOIN users ON questions.user_id = users.id
LEFT JOIN topic_mapping ON questions.id = topic_mapping.question_id
WHERE topic_mapping.topic_id =49
OR topic_mapping.topic_id =50
GROUP BY questions.id
LIMIT 0 , 30

2 个答案:

答案 0 :(得分:1)

要查找已分配两个主题的问题,请测试在HAVING子句中找到的不同主题的数量。此数字应与您在WHERE子句中包含的主题数相匹配。

SELECT questions. * , posts.post, posts.id AS post_id, posts.created, users.id AS user_id, users.username, users.rep
FROM questions
LEFT JOIN posts ON questions.id = posts.question_id
LEFT JOIN users ON questions.user_id = users.id
LEFT JOIN topic_mapping ON questions.id = topic_mapping.question_id
WHERE topic_mapping.topic_id IN (49,50)
GROUP BY questions.id
HAVING COUNT(DISTINCT topic_mapping.topic_id) = 2
LIMIT 0 , 30

答案 1 :(得分:1)

要获取问题ID,请使用HAVING子句:

SELECT
  questions.id
FROM questions LEFT JOIN topic_mapping ON questions.user_id = topic_mapping.question_id
WHERE topic_id = 49 OR topic_id = 50
GROUP BY questions.id
HAVING COUNT(DISTINCT topic_id) = 2

结果是一个问题ID列表,然后可以将其与questions.id上的其余查询联系起来,以检索GROUP BY中未包含的其余列。完整的事情看起来像:

SELECT 
  questions.* , 
  posts.post,
  posts.id AS post_id,
  posts.created, 
  users.id AS user_id,
  users.username, 
  users.rep
FROM questions
JOIN (
    /* subquery gets the posts with 2 topics */
    SELECT
      questions.id
    FROM questions LEFT JOIN topic_mapping ON questions.user_id = topic_mapping.question_id
    WHERE topic_id = 49 OR topic_id = 50
    GROUP BY questions.id
    HAVING COUNT(DISTINCT topic_id) = 2
) qtopics ON questions.id = qtopics.id
LEFT JOIN posts ON questions.id = posts.question_id
LEFT JOIN users ON questions.user_id = users.id
LIMIT 0 , 30