3

I have a table with two columns;

CREATE TABLE IF NOT EXISTS `QUESTION_CATEGORY_RELATION` (
  `question_id` int(16) NOT NULL,
  `category_id` int(16) NOT NULL,
  KEY `category_id` (`category_id`),
  KEY `question_id` (`question_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO `QUESTION_CATEGORY_RELATION` (`question_id`, `category_id`) VALUES
(1, 2),
(1, 3),
(2, 1),
(2, 2);

enter image description here

I want to create a query that will search for a question_id with content_id 2 and content_id 3

e.g.:

SELECT *  
FROM `QUESTION_CONTENTS_REL` 
WHERE `content_id` = 2 AND `content_id` = 3
4

3 回答 3

3
SELECT question_id
FROM QUESTION_CONTENTS_REL
WHERE content_id in (2, 3)
group by question_id
having count(distinct content_id) = 2
于 2012-10-25T11:24:55.423 回答
1

你可以试试这个:

SELECT q1.question_id 
FROM `QUESTION_CONTENTS_REL` q1
JOIN `QUESTION_CONTENTS_REL` q2 on q1.question_id=q2.question_id
WHERE q1.`content_id` = 2 
AND q2.`content_id` = 3

这不是最好的解决方案,因为它有一个 JOIN,例如在 Oracle 中,我会这样做:

SELECT q.question_id 
FROM `QUESTION_CONTENTS_REL` q
GROUP BY q.`question_ID`
HAVING SUM(case when q.`content_id` = '2' then 1 else 0 end)>0 
AND SUM(case when q.`content_id` = '2' then 1 else 0 end)>0 
于 2012-10-25T11:52:04.030 回答
1

我可能会误解,但我认为您正在寻找OR相反,因为 content_id 是关键

SELECT * FROM QUESTION_CONTENTS_REL WHERE `content_id`= 2 OR `content_id` = 3
于 2012-10-25T11:27:07.530 回答