奇怪的MySQL查询结果,聚合函数在coalesce内(ifnull也是)

时间:2017-02-27 14:16:22

标签: mysql mariadb

我们有什么表

id  where_id    price
1      1          1
2      2          2

和sql查询:

select
t_o.*,
coalesce(
  (
      select 
             t_o2.price 
      from test_objects t_o2 where t_o2.where_id = t_o.where_id 
      order by t_o2.price asc limit 1
  )
  ,min(t_o.price)
) as WrongColumn
from test_objects t_o
where t_o.where_id in (1,2)

它返回:

id  where_id    price   WrongColumn
1      1          1         2

为什么这个查询返回ID = 1和WrongColumn = 2,如果第二个和第三个(见下面右下方)查询返回ID = 1且WrongColumn = 1(而不是2)的同一行?

第二个查询:

select
t_o.*,
coalesce(
  (
      select 
             t_o2.price 
      from test_objects t_o2 where t_o2.where_id = t_o.where_id 
      order by t_o2.price asc limit 1
  ),
  t_o.price
) as WrongColumn
from test_objects t_o
where t_o.where_id in (1,2)

返回:

id  where_id    price   WrongColumn
1      1          1          1
2      2          2          2

第三个查询:

select
t_o.*,
coalesce(
  (
      select 
             t_o2.price 
      from test_objects t_o2 where t_o2.where_id = t_o.where_id 
      order by t_o2.price asc limit 1
  )
) as WrongColumn
,min(t_o.price)
from test_objects t_o
where t_o.where_id in (1,2)

返回:


id  where_id    price   WrongColumn min(t_o.price)
1      1          1         1             1

创建表的SQL就在这里:

CREATE TABLE `test_objects` (
  `id` int(11) NOT NULL,
  `where_id` int(11) NOT NULL,
  `price` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

INSERT INTO `test_objects` (`id`, `where_id`, `price`) VALUES
(1, 1,  1),
(2, 2,  2);

1 个答案:

答案 0 :(得分:0)

您的问题是您在主查询中使用聚合函数(min(t_o.price))。这会将整个结果集折叠为仅一行。

为什么不这样做:

test