需要MYSQL查询才能选择特定的子行

时间:2017-08-30 12:17:04

标签: mysql

FX。,给出篮子和水果的表格,寻找一个返回包含 ONLY 两个特定水果的basket_id的查询。

EX 表:水果

basket_id | fruit
_________________
1         | apple
1         | orange
1         | pear

2         | apple
2         | orange

3         | apple
3         | pear

鉴于上表,我正在寻找一个返回basket_id的查询, ONLY 包含水果" apple"和" orange",这只是第2行。应排除购物篮ID 1,因为它还包含" pear"。

非常感谢您的帮助。

5 个答案:

答案 0 :(得分:2)

请注意,对于示例表,我添加了另一个篮子,它是basket_id = 4,只有两个苹果,它将是查询的强大测试样本。

WITH ABC  --sample table
AS
(
SELECT 1 as basket_id, 'Apple' as fruit
UNION ALL 
SELECT 1 as basket_id, 'Orange' as fruit
UNION ALL 
SELECT 1 as basket_id, 'Pear' as fruit
UNION ALL 
SELECT 2 as basket_id, 'Apple' as fruit
UNION ALL 
SELECT 2 as basket_id, 'Orange' as fruit
UNION ALL 
SELECT 3 as basket_id, 'Apple' as fruit
UNION ALL 
SELECT 3 as basket_id, 'Pear' as fruit
UNION ALL 
SELECT 4 as basket_id, 'Apple' as fruit
UNION ALL 
SELECT 4 as basket_id, 'Apple' as fruit
)
 --main query:   
SELECT basket_id FROM
(
 SELECT *,CASE WHEN fruit in ('Apple','Orange') THEN 1 ELSE 0 END AS row_check
 FROM ABC
 ) as A
GROUP BY basket_id
HAVING COUNT(DISTINCT row_check) =1 -- make sure there is no other fruit 
AND COUNT(DISTINCT fruit) >1   -- make sure there are at least one apple and one orange
  

输出:basket_id 2

答案 1 :(得分:1)

select
  f.basket_id,
  (select count(1) from fruits where basket_id = f.basket_id) as fruits_in_basket,
  (select count(1) from fruits where basket_id = f.basket_id and fruit in ("apple", "orange")) as specific_fruits_in_basket
from
  fruits as f
group by f.basket_id
having fruits_in_basket = specific_fruits_in_basket

这是一个小提琴:http://sqlfiddle.com/#!9/f4ae3c/37/0

答案 2 :(得分:0)

SELECT DISTINCT basket_id 
FROM fruits f
WHERE 
   NOT EXISTS (SELECT 1 FROM fruits f1 WHERE f.basket_id=f1.basket_id AND f1.fruit NOT IN ('apple', 'orange'))
AND
   (SELECT count(*) FROM fruits f2 WHERE f.basket_id=f2.basket_id AND f2.fruit='apple')=1
AND 
   (SELECT count(*) FROM fruits f3 WHERE f.basket_id=f3.basket_id AND f3.fruit='orange')=1;

我已经在您的示例中测试了查询。 Demo

答案 3 :(得分:0)

如果可以将项目列表用作有序列表,您可以选择'apple,orange',那么您可以使用以下内容。

SELECT f.basket_id, f.fruit
FROM fruits f
     INNER JOIN (
         SELECT basket_id, GROUP_CONCAT(fruit order by fruit) as a
         FROM fruits
         GROUP BY basket_id
         HAVING a = 'apple,orange'
     ) f1 ON f.basket_id = f1.basket_id

这是fiddle

答案 4 :(得分:-1)

SELECT DISTINCT(basket_id) 
FROM basket
where fruit IN ('apple', 'orange');