pingcap / tidb

TiDB is an open-source, cloud-native, distributed, MySQL-Compatible database for elastic scale and real-time analytics. Try AI-powered Chat2Query free at : https://www.pingcap.com/tidb-serverless/
https://pingcap.com
Apache License 2.0
36.88k stars 5.81k forks source link

If group by key contains constant columns, the constant columns should be removed from group by key #53994

Open windtalker opened 3 months ago

windtalker commented 3 months ago

Enhancement

Consider the following cases

1. select count(*), id from test where id = 1 group by id
2. select count(*), id, value from test where id = 1 group by id, value

If there is no implict cast in expr id = 1, then id should be a constant column after filter, it can be removed from the group by keys, that is the optimizer should rewrite the sql to

1. select count(*), first_row(id) from test where id = 1
2. select count(*), first_row(id), value from test where id = 1 group by value
winoros commented 2 months ago

For the first query, we cannot remove the group-by directly because the result is different for an empty table whether it's a group-by agg or just a global agg.

dash12653 commented 1 month ago

It seems that an RBO rule needs to be added. I will try to handle this issue.