我有一个包含两列的表格;
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);
我想创建一个将使用content_id 2和content_id 3
搜索question_id的查询e.g:
SELECT *
FROM `QUESTION_CONTENTS_REL`
WHERE `content_id` = 2 AND `content_id` = 3
答案 0 :(得分:3)
SELECT question_id
FROM QUESTION_CONTENTS_REL
WHERE content_id in (2, 3)
group by question_id
having count(distinct content_id) = 2
答案 1 :(得分:1)
我可能会错过解释,但我认为你正在寻找OR
,因为content_id是一个关键
SELECT * FROM QUESTION_CONTENTS_REL WHERE `content_id`= 2 OR `content_id` = 3
答案 2 :(得分: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