Mysql使用多个条件选择数据

发布于 2024-09-11 05:26:26 字数 265 浏览 4 评论 0原文

我有一个像

id   fid
20    53
23    53
53    53

Here 这样的表,当我的条件类似于 .. where fid=53 and id in(20,23,53) 时,我需要返回 true 而且我还需要在 ....其中 fid=53 且 id in(20,24,53) 时返回 false。 但上述条件不满足我的要求。两个查询返回相同的值(true)。请帮助我继续。

I have a table like

id   fid
20    53
23    53
53    53

Here I need to return true when my condition is something like .. where fid=53 and id in(20,23,53)
and also I need to return false when....where fid=53 and id in(20,24,53).
But the above condition not satisfy my requirement.Both queries returns same value(true).Please help me to go forward.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

他夏了夏天 2024-09-18 05:26:26

我相信您要求的是查询找到与所有值 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;

I believe what you're asking for is for the query to find the fid that is associated with ALL values 20,23,53 and if not, then that fid isn't returned by the query.

There are two common solutions to this in SQL.

First the one that I recommend for 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);

Here's another solution that uses group by instead of self-joins, but tends to perform worse in MySQL:

SELECT t.fid
FROM mytable t
WHERE t.id IN (20,23,53)
GROUP BY t.fid
HAVING COUNT(*) = 3;
倚栏听风 2024-09-18 05:26:26

也许是子查询?

SELECT id, fid FROM table
WHERE fid = 53 AND
id IN ( SELECT id FROM table WHERE id IN(20,24,53))

maybe a subquery?

SELECT id, fid FROM table
WHERE fid = 53 AND
id IN ( SELECT id FROM table WHERE id IN(20,24,53))
孤城病女 2024-09-18 05:26:26

根据您的示例条件,单个查询不可能:(。
因为 where fid=53 and id in(20,23,53) 对于 fid=53 和 id =20,53 返回 true
同样,对于 fid=53 和 id =20,53,where fid=53 and id in(20,24,53) 为 false,

唯一的区别在于 id=23 和 id=24。所以你可以通过两个差异查询来完成。但有时它们会对相同的数据返回 true 和 false。

我认为你需要再考虑一下你的问题。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文