微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

我正在尝试在MySQL中编写查询,并在PHP输出结果,但事实证明这相当困难.

我有一个包含3列的表格(是的,我知道这不是最好的数据库布局,但是我无法更改此设置,客户端使用该数据库以这种精确布局使用其他软件)

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

问题是,当客户在表格上填写“苹果”和“ 2”时,它将返回所有装有2个苹果的篮子.我需要的是一种声明,该声明将只接受确切的产品及其数量,以退还该成分所属的一个篮子,或者完全不退.

因此,即使Fruitbasket1中有1个梨和2个苹果,但如果客户未指定其他部分(即5个葡萄),也不应将结果作为Fruitbasket1.

解决方法:

查询将返回唯一产品为2个Apple的所有包装

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐