我确实陷入了困境。
例如我的表是
genre_id series_id
1 1
1 2
2 5
4 1
2 4
3 3
我希望得到genre_id
,其中包含series_id
1 。
因此,我的查询仅返回genre_id
4 而非genre_id
1
但是这个查询
SELECT genre_id FROM test
WHERE genre_id IN (1)
GROUP BY series_id
HAVING COUNT(*) = 1
返回genre_id
1 和 2
答案 0 :(得分:0)
/*
drop table t;
create table t (genre_id int, series_id int);
insert into t values
(1, 1),
(1, 2),
(2, 5),
(4, 1),
(2, 4),
(3, 3);
*/
select s.genre_id
from
(
select genre_id , max(series_id) maxsid
from t
group by genre_id
) s
where s.maxsid = 1;
结果
+----------+
| genre_id |
+----------+
| 4 |
+----------+
答案 1 :(得分:0)
SELECT x.genre_id
FROM my_table x
LEFT
JOIN my_table y
ON y.genre_id = x.genre_id
AND y.series_id NOT IN(1)
WHERE y.genre_id IS NULL
GROUP
BY x.genre_id HAVING COUNT(*) = 1;
答案 2 :(得分:-1)
好像你使用了错误的查询:
SELECT series_id FROM test WHERE genre_id IN (1) GROUP BY series_id HAVING COUNT(*) = 1
使用
SELECT genre_id FROM test WHERE series_id IN (1) GROUP BY genre_id HAVING COUNT(*) = 1