我有以下mysql查询:
insert into my_table (col_a, col_b)
select
col_a,
col_b,
if(foo, bar, baz) as my_alias
from qux
group by my_alias
having my_alias is not null
如果没有select
生成的字段my_alias
,我怎么能重写查询?
例如,我正在尝试实现类似这样的东西,我只在col_a,col_b上插入:
insert into my_table (col_a, col_b)
select
col_a,
col_b
from qux
group by if(foo, bar, baz) as my_alias
having my_alias is not null
我找到了一些先前的答案,通过进行子选择来完成。没有一个可以实现吗?提前谢谢。
答案 0 :(得分:1)
MySQL允许GROUP BY子句中的表达式,因此别名是 不必要:
SELECT id, FLOOR(value/100) FROM tbl_name GROUP BY id, FLOOR(value/100);
HAVING在结尾处过滤掉NULL记录。我们也可以使用WHERE来过滤掉正手的NULL记录。这意味着这应该有效:
insert into my_table (col_a, col_b)
select
col_a,
col_b
from qux
where if(foo, bar, baz) is not null
group by if(foo, bar, baz)