MySQL奇怪的结果是子查询,内连接和order by

时间:2015-09-01 10:41:51

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

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

这是对问题的清晰再现:

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。

1 个答案:

答案 0 :(得分:0)

似乎要求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

所以看起来好像它应该是错误而不是错误的结果。