【问题标题】:MySQL strange results with subquery, inner join and order byMySQL 子查询、内连接和排序的奇怪结果
【发布时间】:2015-11-26 13:40:15
【问题描述】:

我遇到了一种奇怪的查询行为,我不知道为什么它没有按预期工作。

这是问题的清晰再现:

create table A (
  id int not null auto_increment,
  primary key (id)
) ENGINE=InnoDB;

create table B (
  id int not null auto_increment,
  a_id int not null,
  qty double not null,
  primary key (id),
  key IDX_A (a_id)
) ENGINE=InnoDB;

create table C (
  id int not null auto_increment,
  b_id int not null,
  qty double not null,
  primary key (id),
  key IDX_B (b_id)
) ENGINE=InnoDB;

insert into A (id) values (1);

insert into B (id, a_id, qty) values (1, 1, 10);
insert into B (id, a_id, qty) values (2, 1, 15);
insert into B (id, a_id, qty) values (3, 1, 2);

insert into C (id, b_id, qty) values (1, 1, 7);
insert into C (id, b_id, qty) values (2, 1, 3);
insert into C (id, b_id, qty) values (3, 2, 3);

ALTER TABLE `B` ADD CONSTRAINT FK_BA FOREIGN KEY (a_id) REFERENCES A (id);
ALTER TABLE `C` ADD CONSTRAINT FK_CB FOREIGN KEY (b_id) REFERENCES B (id);

这里是查询:

SELECT 
  b.id as b_id,
  b.qty as b_qty
FROM 
  B b
  INNER JOIN A a ON B.a_id = A.id 
WHERE 
  EXISTS (
    SELECT 1 FROM C c 
    WHERE 
      c.b_id = b.id 
    HAVING 
      sum(c.qty) = b.qty
  )
ORDER BY b.id

我期待这个结果:

+------+-------+
| b_id | b_qty |
+------+-------+
|    1 |    10 |
+------+-------+

但是这个查询以某种方式给出了一个空的结果集。

有点兴趣:

当我从 select 子句中删除“b.qty”时,它运行良好。 如果我删除了内部连接或 order by 子句,它也可以工作。

是我失败了还是这是一个错误?

在 5.6.26 和 5.5.34 上测试。

【问题讨论】:

    标签: mysql subquery sql-order-by inner-join having


    【解决方案1】:

    似乎要求 HAVING 子句中的列包含在 SELECT 列表中,以下工作:

    SELECT 
      b.id AS b_id,
      b.qty AS b_qty
    FROM 
      B b
      INNER JOIN A a ON b.a_id = a.id 
    WHERE 
      EXISTS (
        SELECT b.qty,SUM(c.qty) FROM C c 
        WHERE 
          c.b_id = b.id 
        HAVING 
          SUM(c.qty) = b.qty
      )
    ORDER BY b.id;
    

    看起来还是很奇怪的行为。 分析它我发现如果你不包含列,拉出子选择它实际上会出错,这会出错:

    SELECT 1 FROM C c ,B b
    WHERE 
    c.b_id = b.id 
    GROUP BY c.b_id
    HAVING 
    SUM(c.qty) = b.qty
    

    这不是:

    SELECT * FROM C c ,B b
    WHERE 
    c.b_id = b.id 
    GROUP BY c.b_id
    HAVING 
    SUM(c.qty) = b.qty
    

    所以看起来这个错误是它应该给出一个错误而不是错误的结果。

    【讨论】:

    • 感谢您的回复!我仔细查看了文档,所以我重写了我的查询,因为我误解了 HAVING 子句的功能。无论如何,这仍然是一种奇怪的行为,但是您的解释非常有帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-23
    • 1970-01-01
    • 1970-01-01
    • 2017-02-26
    • 2018-09-01
    • 2018-01-12
    • 2021-09-25
    相关资源
    最近更新 更多