表
+------+-----------+
| ID | subject |
+------+-----------+
| 1 | science |
| 1 | maths |
| 2 | maths |
| 3 | science |
| 4 | science |
| 4 | biology |
| 4 | maths |
| 5 | biology |
| 5 | economics |
+------+-----------+
9 rows in set (0.00 sec)
上表要查询以科目和科学为主题的唯一ID
答案 0 :(得分:0)
您可以在下面尝试-
select distinct id
from tablename
where subject in ('science', 'maths')
having count(distinct subject)=2
答案 1 :(得分:-1)
您在这里:
SELECT
DISTINCT(`ID`)
FROM
`TABLE`
WHERE
`subject` IN ('science', 'maths');
已更新:
CREATE TABLE test (
id INT ,
subject varchar(30)
);
INSERT INTO test (id, subject) VALUES
(1,'science'),
(1,'maths'),
(2,'maths'),
(3,'science'),
(4,'science'),
(4,'biology'),
(4,'maths'),
(5,'biology'),
(5,'economics');
SELECT
DISTINCT(a.id)
FROM
test a
LEFT JOIN test b on b.id=a.id AND b.subject IN ('science', 'maths')
WHERE
a.subject='science' AND b.subject='maths';
/*output: 1, 4*/
希望这会有所帮助