gpt4 book ai didi

MySQL ONLY IN() 等效子句

转载 作者:可可西里 更新时间:2023-11-01 07:16:37 25 4
gpt4 key购买 nike

我在这里给出了我的问题的一个非常抽象的版本,所以请耐心等待。我有一个查询将检查特定主体是否具有相同类型的某些多个参数。例如,就巧克力而言,男孩有多项选择。但是,我想从 table 上选出恰好有我提到的巧克力的男孩。不多不少,不是“LIKE”或“IN()”。

SELECT boy_id from boys_chocolates WHERE chocolate_id ONLY IN('$string');

..当然,“$string”是一个 PHP 变量,其中只包含我想用来吸引男孩的那些巧克力的逗号分隔值。

我知道这是无效的 MySQL 语句,但是否有任何有效的等价物?

编辑:

这是更全面的查询,它在特殊情况下获取记录,但并非总是如此。

SELECT boys.* FROM schools_boys INNER JOIN boys ON boys.boy_id=schools_boys.boy_id
INNER JOIN chocolates_boys a ON a.boy_id=boys.boy_id INNER JOIN schools
ON schools.school_id=schools_boys.school_id WHERE a.chocolate_id IN(1000,1003)
AND
EXISTS
(
SELECT 1
FROM chocolates_boys b
WHERE a.boy_id=b.boy_id
GROUP BY boy_id
HAVING COUNT(DISTINCT chocolate_id) = '2'
)

GROUP BY schools_boys.boy_id HAVING COUNT(*) = '2'

Boys Table
+--------+-------------+
| id | boy |
+--------+-------------+
| 10007 | Boy1 |
| 10008 | Boy2 |
| 10009 | Boy3 |
+--------+-------------+

Chocolates Boys Table
+----+---------+--------------+
| id | chocolate_id | boy_id |
+----+--------------+---------+
| 1 | 1000 | 10007 |
| 2 | 1003 | 10007 |
| 3 | 1006 | 10007 |
| 4 | 1000 | 10009 |
| 5 | 1001 | 10009 |
| 6 | 1005 | 10009 |
+----+--------------+---------+

当我单独选择 1000 来拉两个男孩(或)1000 和 1003 来拉出 ID 为 10007 的男孩时,没有任何反应。

最佳答案

这个问题叫做Relational Division

SELECT boy_id 
FROM boys_chocolates
WHERE chocolate_id IN ('$string')
GROUP BY boy_id
HAVING COUNT(DISTINCT chocolate_id) = ? -- <<== number of chocolates specified

例子:

SELECT boy_id 
FROM boys_chocolates
WHERE chocolate_id IN (1,2,3,4)
GROUP BY boy_id
HAVING COUNT(DISTINCT chocolate_id) = 4

但是,如果 chocolate_id 对于每个 boy_id 都是唯一的,则 DISTINCT 关键字是可选的。

SELECT boy_id 
FROM boys_chocolates
WHERE chocolate_id IN (1,2,3,4)
GROUP BY boy_id
HAVING COUNT(*) = 4

更新 1

...我想从 table 上选择那些正是我提到的巧克力的男孩。不多不少……

SELECT boy_id 
FROM boys_chocolates a
WHERE chocolate_id IN (1,2,3,4) AND
EXISTS
(
SELECT 1
FROM boys_chocolates b
WHERE a.boy_ID = b.boy_ID
GROUP BY boy_id
HAVING COUNT(DISTINCT chocolate_id) = 4
)
GROUP BY boy_id
HAVING COUNT(*) = 4

关于MySQL ONLY IN() 等效子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16461707/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com