SQL 查询过滤到仅适用的行

SQL query filter down to only applicable rows

我如何 select 这样的查询?我有点困惑,因为这 return 什么都没有,因为任何行都不满足任何“where 子句”..

我想要的是生成计数 1 的查询的答案。并且 productId 是“1”...感谢您的帮助!

SELECT productId where carId=12 and objectiveId=15 and locationId=11

+----+-----------+------------+-------------+------------+
| id | productId | carId      | objectiveId | locationId |
+----+-----------+------------+-------------+------------+
|  1 |         1 |         12 |           0 |          0 |
|  2 |         1 |          0 |          15 |          0 |
|  3 |         1 |          0 |           0 |         11 |
|  4 |         2 |         11 |           0 |          0 |
|  5 |         2 |          0 |          10 |          0 |
|  6 |         2 |          0 |           0 |         14 |
+----+-----------+------------+-------------+------------+

这里的一种方法是按产品聚合,然后断言各种 ID 的存在:

SELECT productId
FROM yourTable
GROUP BY productId
HAVING SUM(carId = 12) > 0 AND SUM(objectiveId = 15) > 0 AND SUM(locationId = 11) > 0;

为了解释上述内容,HAVING 子句在 GROUP BY 聚合发生后计算。也就是说,您在 HAVING 子句中看到的任何逻辑都处理每个产品的记录组(并且 而不是 单个产品记录本身)。表达式 SUM(carId = 12) 基本上计算 cardId = 12 的次数。对于每个匹配的产品(以及其他两个条件),您希望此条件至少为真一次。

使用 or 代替 and with Distinct 以 select 独特的 productid。

SELECT distinct productId from mytable where carId=12 or objectiveId=15 or locationId=11

link示例:

create table mytable ( id int , productId int, carId int, objectiveId int, locationId int);

insert into mytable value( 1 ,1 ,12 ,  0 , 0 );
insert into mytable value( 2 ,1 , 0 , 15 , 0 );
insert into mytable value( 3 ,1 , 0 ,  0 ,11 );
insert into mytable value( 4 ,2 ,11 ,  0 , 0 );
insert into mytable value( 5 ,2 , 0 , 10 , 0 );
insert into mytable value( 6 ,2 , 0 ,  0 ,14 );

查询:

SELECT distinct productId from mytable where carId=12 or objectiveId=15 or locationId=11
productId
1

db<>fiddle here