无法从MySQL查询中获得所需的结果

时间:2014-09-23 14:19:14

标签: php mysql sql

我正在尝试使用PHP中的输出在MySQL中编写查询,但事实证明这很难。

我有一个包含3列的表(是的我知道这个数据库的布局不是最好的,但是我无法改变这个,客户端有其他软件使用这个db这个确切的布局)

Amount - Product - Package 
2      - Apple   - Fruitbasket1
1      - Pear    - Fruitbasket1
5      - Grape   - Fruitbasket1
2      - Apple   - Fruitbasket2
1      - Pear    - Fruitbasket2
9      - Banana  - Fruitbasket2

到目前为止,我提出了这个问题:

SELECT package 
FROM `data` 
WHERE package IN 
(
  SELECT package 
  FROM `data` 
  WHERE product = 'apple' AND amount = '2'
) 
AND package IN 
(
  SELECT package 
  FROM `data` 
  WHERE product = 'pear' AND amount ='1'
) 
AND package IN 
(
  SELECT package 
  FROM `data` 
  WHERE product = 'grape' AND amount = '5'
) 
LIMIT 0,1

问题是,当客户在表单上填写“apple”和“2”时,它将返回包含2个苹果的所有篮子。我需要的是一份声明,它只接受确切的产品及其数量,以返回那些成分所属的一篮子,或者什么都没有。

所以即使1个梨和2个苹果在Fruitbasket1中,如果客户没有指定其他部分,即5个葡萄,它也不应该给Fruitbasket1。

2 个答案:

答案 0 :(得分:2)

此查询将返回唯一产品为2个苹果的所有包

select package from `data`
group by package
having count(case when amount = 2 and product = 'Apple' then 1 end) = 1
and count(*) = 1

如果您想要1个梨和2个苹果,例如

select package from `data`
group by package
having count(
  case 
    when (amount = 2 and product = 'Apple') or (amount = 1 and product = 'Pear') 
    then 1 
  end) = 2
and count(*) = 2

您也可以将其写为

select package from `data`
group by package
having count(case when amount = 2 and product = 'Apple' then 1 end) = 1
   and count(case when amount = 1 and product = 'Pear' then 1 end) = 1
   and count(*) = 2

答案 1 :(得分:2)

我只有Oracle方便,所以你可能需要稍微调整一下语法,但是按照原来的风格,我已经添加了一个"而不是"确保篮子只包含您正在寻找的水果的部分。以下是一些带有几个示例的插入内容:

create table data (amount integer, product varchar(12), package varchar(16));

insert into data values (2, 'Apple', 'Fruitbasket1');
insert into data values (1, 'Pear', 'Fruitbasket1');
insert into data values (5, 'Grape', 'Fruitbasket1');
insert into data values (2, 'Apple', 'Fruitbasket2');
insert into data values (1, 'Pear', 'Fruitbasket2');
insert into data values (9, 'Banana', 'Fruitbasket2');
insert into data values (2, 'Apple', 'Fruitbasket3');
insert into data values (2, 'Apple', 'Fruitbasket4');
insert into data values (1, 'Pear', 'Fruitbasket4');


SELECT package 
FROM data 
WHERE package IN 
(
  SELECT package 
  from data 
  WHERE product = 'Apple' AND amount = '2'
)
and package not in
(
  SELECT package 
  from data 
  WHERE product <> 'Apple'
)
group by package
;


SELECT package 
FROM data 
WHERE package IN 
(
  SELECT package 
  from data 
  WHERE product = 'Apple' AND amount = '2'
) 
AND package IN 
(
  SELECT package 
  FROM data 
  WHERE product = 'Pear' AND amount ='1'
) 
and package not in
(
  SELECT package 
  from data 
  WHERE product <> 'Apple' and product <> 'Pear'
)
group by package
;