说我有这些表:
create table letter (id_letter bigint, id_group_table bigint, letter char(1));
create table group_table (id_group_table bigint, id_whatever bigint, champion char(1));
create table whatever (id_whatever bigint);
我想更新group_table
,以便我可以在champion
列中设置letter
表中与{{1}中的每一行相关的字母数最多的字母}}。今天我必须在我的应用程序中迭代group_table
中的所有行并对每行运行查询以发现最常用的字母...我想在一次更新中执行此操作,是否可能?
这是我尝试(并且不起作用)的内容:
group_table
MySQL不允许我使用update group_table gt
set gt.champion =
(
select inner_champ from
(
select le.letter as inner_champ, count(*) from letter le
where le.id_group_table = gt.id_group_table
group by le.letter
order by count(*) desc
limit 1
)
)
where gt.id_whatever in (1,2,3,4);
引用子查询中的group_table
...是否可以这样做?
谢谢!
答案 0 :(得分:1)
您可以在内部查询中单独使用JOIN
进行group_table
,如下所示
update group_table
join
(
select letter,
id_group_table,
count(distinct id_group_table) as occurences
from letter
group by letter
having max(occurences)
) tab on group_table.id_group_table = tab.id_group_table
set champion = tab.letter
where group_table.id_whatever in (1,2,3,4);
答案 1 :(得分:0)
您可以尝试使用连接而不是where。尝试类似的东西:
select inner_champ from
(
select le.letter as inner_champ, count(*) from letter le
left join group_table gt2 on le.id_group_table = gt2.id_group_table
group by le.letter
order by count(*) desc
)
答案 2 :(得分:0)
update group_table
join
(
select tab1.letter, tab1.id_group_table from
(
select letter,
id_group_table,
count(letter) as occurrences
from letter
group by id_group_table, letter
order by occurrences desc
) tab1
group by tab1.id_group_table having max(tab1.occurrences)
) tab2 on group_table.id_group_table = tab2.id_group_table
set champion = tab2.letter
where group_table.id_whatever in (1,2,3,4);