Mysql 如何在集合子查询中引用外部表?
假设我有这些桌子:Mysql 如何在集合子查询中引用外部表?,mysql,sql,Mysql,Sql,假设我有这些桌子: 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\u表,以便在champion列中
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\u表
,以便在champion
列中设置与group\u表
中的每一行相关的字母
表中出现次数最多的字母。今天,我必须在我的应用程序中迭代group\u表中的所有行
,并对每一行运行一个查询,以发现最常用的字母是什么。。。我想在一次更新中做到这一点,有可能吗
以下是我正在尝试的(但不起作用):
MySQL不允许我使用gt.id\u group\u表
在子查询中引用group\u表
。。。有可能吗
谢谢 您可以尝试使用连接而不是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
)
您可以在如下所示的内部查询中分别使用
group\u表执行JOIN
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);
此子查询将为我提供所有字母分组,按出现次数排序,独立于更新将处理的每一行。我需要子查询只返回一行,与updateok中的每一行相关。在这种情况下,您可以向查询中添加“Top 1”,或者可以像第一次查询中那样使用“Limit 1”,这样我可以得到任何gt
行中出现次数最多的字母。我需要出现最多的字母,它只与更新处理的行相关。但这样子查询就与gt1
无关。假设更新将从gt1
更新第1、2、3、4行。在更新的第一次迭代中,它将更新第1行。假设第1行具有id\u group\u表
=77。子查询是如何获取与id\u group\u表
77相关的内容的?谢谢,但我仍然看不到当前更新行与子查询结果之间的关系。这样,将更新group\u表
中的所有行,得到gt.id\u中出现次数最多的字母,无论是在(1,2,3,4)
中,这对我来说都无关紧要。我真正需要的是,当前正在处理的行与字母表的更新之间的连接。我可以删除此where
条件,它与我的问题没有任何关系。您可以使用内部结果集执行连接,但由于您的内部查询只返回1行,因此没有执行此操作。此外,如果没有WHERE条件,那么您打算更新所有行。。。是吗?是的,但我认为你遗漏了一些东西:group\u表
中的每一行都有一个冠军。此champion是在字母表中重复多次的字母,与此行相连。我不想要最重复的信。。。那很容易!如果有人想玩,group\u表
Schema中的每一行,我需要重复次数最多的字母:
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);
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);