【发布时间】: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