这是一种挑战。预期的产量,所有水果都来自ny或ak状态,如果商标好=价格10和坏=价格20和OK =价格40.那么,来自纽约州的苹果,标记好坏匹配价格10和20,和苹果没有标记OK行,所以无需比较。香蕉标记坏=价格20,但OK价格不等于40,所以我将排除香蕉。梨匹配OK =价格40和州= ny并且没有好的和坏的标记行。因此,我的输出应该是苹果和梨。我该怎么做?
<?php
/*
fruit state price mark
apple ny 10 good
apple ny 20 bad
banana ny 20 bad
banana ny 30 OK
pear ny 40 OK
berry pa 10 good
*/
/*this is my best query but fail to do what I expected*/
SELECT fruit FROM table WHERE state IN ('ny','ak') AND mark IN ('good', 'bad', 'OK') AND price IN ( '10','20','40') GROUP BY fruit
?>
答案 0 :(得分:0)
你应该在哪里和/或条件
你应该使用一对不在
select distinct fruit from my_table
where fruit not in (select distinct fruit from my_table
where (mark, price) not in (select 'good', 10 from dual
union
select 'bad, 20 from dual
union
select 'OK', 40 from dual))
state IN ('ny','ak') ;
答案 1 :(得分:0)
可能返回的潜在水果列表,因为一行符合规范:
SELECT t.fruit
FROM `table` t
WHERE t.state IN ('ny','ak')
AND ( ( t.mark = 'good' AND t.price = 10 )
OR ( t.mark = 'bad' AND t.price = 20 )
OR ( t.mark = 'OK' AND t.price = 40 )
)
GROUP BY t.fruit
我们不想返回的水果列表,因为有一行不符合规范:
SELECT t.fruit
FROM `table` t
WHERE t.state IN ('ny','ak')
AND NOT ( t.mark = 'good' AND t.price = 10 )
AND NOT ( t.mark = 'bad' AND t.price = 20 )
AND NOT ( t.mark = 'OK' AND t.price = 40 )
GROUP BY t.fruit
请注意,这还包括mark列的值不是good,bad或OK的行。如果我们想忽略具有其他mark值的行,那么我们将添加...
AND t.mark IN ('good','bad','OK')
这给了我们两套。我们可以将它们与反连接操作结合起来。作为一个示例,如果我们有表fruit_to_include
和fruit_to_exclude
...
SELECT i.fruit
FROM fruit_to_include i
LEFT
JOIN fruit_to_exclude e
ON e.fruit = i.fruit
WHERE e.fruit IS NULL
ORDER BY i.fruit
我们可以使用内嵌视图替换这些占位符表名称,使用提供水果的查询和要排除的水果。这里唯一的区别是用(MySQL所指的)派生表替换虚拟表名。
SELECT i.fruit
FROM -- fruit_to_include
( SELECT t.fruit
FROM `table` t
WHERE t.state IN ('ny','ak')
AND ( ( t.mark = 'good' AND t.price = 10 )
OR ( t.mark = 'bad' AND t.price = 20 )
OR ( t.mark = 'OK' AND t.price = 40 )
)
GROUP BY t.fruit
) i
LEFT
JOIN -- fruit_to_exclude
( SELECT r.fruit
FROM `table` r
WHERE r.state IN ('ny','ak')
AND r.mark IN ('good','bad','OK')
AND NOT ( r.mark = 'good' AND r.price = 10 )
AND NOT ( r.mark = 'bad' AND r.price = 20 )
AND NOT ( r.mark = 'OK' AND r.price = 40 )
GROUP BY r.fruit
) e
ON e.fruit = i.fruit
WHERE e.fruit IS NULL
ORDER BY i.fruit