ITPub博客

首页 > 数据库 > MySQL > MySQL 除法问题

MySQL 除法问题

翻译 MySQL 作者:神谕丶 时间:2014-08-21 14:40:39 0 删除 编辑
此处用到了Pivoting技术
注:Pivoting技术是指一种可以把行转换为列的技术,在Pivoting的执行过程中可能会用到聚合。
这里讨论的都是静态Pivoting查询,即用户需要提前知道旋转的属性列的值,对于动态Pivoting,需要动态地构造查询字符串。


关系除法问题的解决方案:
(当除数集合中的元素数量较小时,Pivoting可以用于解决关系除法问题)


  1. create table devision(
  2. orderid varchar(10) not null,
  3. productid int not null,
  4. primary key(orderid,productid));


  1. insert into devision select 'A',1;
  2. insert into devision select 'A',2;
  3. insert into devision select 'A',3;
  4. insert into devision select 'A',4;
  5. insert into devision select 'B',2;
  6. insert into devision select 'B',3;
  7. insert into devision select 'B',4;
  8. insert into devision select 'C',3;
  9. insert into devision select 'C',4;
  10. insert into devision select 'D',4;


解释一下:
表devision存储订单中包含的产品,比如A订单所包含的产品ID为1、2、3、4,C订单所包含的产品ID为3、4,以此类推
Pivoting技术可以把每个订单中的产品旋转到单独的列之中。
比如需要查询productid为2、3、4的订单,可以采用以下方法:



  1. select orderid
  2. from(select orderid,
  3.     max(case when productid=2 then 1 end) as p2,
  4.     max(case when productid=3 then 1 end) as p3,
  5.     max(case when productid=4 then 1 end) as p4
  6.     from devision
  7.     group by orderid
  8.     ) p
  9. where p2=1 and p3=1 and p4=1;

得到的结果很显然:



因为只有A和B订单包含产品ID为2、3、4的产品

上sql语句中的派生表P输出结果为:





如果将生成派生表p的语句中的max函数改成count函数,则更加直观:
及若产品存在则返回为1,不存在则返回为0,而不是null。



    1. select orderid
    2. from(select orderid,
    3.     count(case when productid=2 then 1 end) as p2,
    4.     count(case when productid=3 then 1 end) as p3,
    5.     count(case when productid=4 then 1 end) as p4
    6.     from devision
    7.     group by orderid
    8.     ) p
    9. where p2=1 and p3=1 and p4=1;





来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/29773961/viewspace-1255297/ ,如需转载,请注明出处,否则将追究法律责任。

上一篇: MySQL 处理行号
请登录后发表评论 登录
全部评论
微信公众号:神谕的暗影长廊

注册时间:2014-07-28

  • 博文量
    161
  • 访问量
    1195299