我有一张像
id fid
20 53
23 53
53 53
在这里,当我的情况类似于时,我需要返回 true,.. where fid=53 and id in(20,23,53)
并且我需要在 时返回 false ....where fid=53 and id in(20,24,53)
。但上述条件不满足我的要求。两个查询返回相同的值(true)。请帮助我继续前进。
我有一张像
id fid
20 53
23 53
53 53
在这里,当我的情况类似于时,我需要返回 true,.. where fid=53 and id in(20,23,53)
并且我需要在 时返回 false ....where fid=53 and id in(20,24,53)
。但上述条件不满足我的要求。两个查询返回相同的值(true)。请帮助我继续前进。
我相信您要求的是查询找到与所有值 20、23、53 关联的 fid,如果没有,则查询不会返回该 fid。
SQL 中有两种常见的解决方案。
首先是我为 MySQL 推荐的一个:
SELECT t1.fid
FROM mytable t1
JOIN mytable t2 ON t1.fid = t2.fid
JOIN mytable t3 ON t1.fid = t2.fid
WHERE (t1.id, t2.id, t3.id) = (20,23,53);
这是另一个使用 group by 而不是自连接的解决方案,但在 MySQL 中往往表现更差:
SELECT t.fid
FROM mytable t
WHERE t.id IN (20,23,53)
GROUP BY t.fid
HAVING COUNT(*) = 3;
也许是一个子查询?
SELECT id, fid FROM table
WHERE fid = 53 AND
id IN ( SELECT id FROM table WHERE id IN(20,24,53))
According to your example conditions, its not possible with a single query :(.
since where fid=53 and id in(20,23,53)
return true for fid=53 and id =20,53
Similarly, where fid=53 and id in(20,24,53)
is false for fid=53 and id =20,53
the only difference is about id=23 and id=24. So you can do it with two difference query. But sometimes they will return true and false for same data.
I think you need to think about your question once again.