概念疑问:
我尝试过很多东西(MySQL)但是这个更新工作的唯一方法就是我在这里描述的方式。它有效,但我想确定一下:
当我们使用加入更新时,我设置的值来自正在加入的表,有多个加入每行的可能性,更新是否始终是第一个可能的行来进行连接?
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);
insert into whatever values (1);
insert into whatever values (2);
insert into whatever values (3);
insert into whatever values (4);
insert into whatever values (5);
insert into group_table values(1, 1, null); -- champion should be B
insert into group_table values(2, 2, null); -- champion should be C
insert into group_table values(3, 3, null); -- champion should be X
insert into group_table values(4, 4, null); -- champion should be C
insert into group_table values(5, 5, null);
insert into letter values(1,1,'A');
insert into letter values(2,1,'B');
insert into letter values(3,1,'B');
insert into letter values(4,2,'B');
insert into letter values(5,2,'C');
insert into letter values(6,2,'C');
insert into letter values(7,3,'X');
insert into letter values(8,3,'X');
insert into letter values(9,3,'Y');
insert into letter values(10,4,'A');
insert into letter values(11,4,'A');
insert into letter values(12,4,'C');
insert into letter values(13,4,'C');
insert into letter values(14,4,'C');
insert into letter values(15,4,'C');
insert into letter values(16,5,'B');
insert into letter values(17,5,'C');
insert into letter values(18,5,'C');
-- update to set champions for everybody
update group_table
join
(select letter,
id_group_table,
count(letter) as occurences
from letter
group by id_group_table, letter
order by occurences desc
) 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);
http://sqlfiddle.com/#!2/6ea061/1
谢谢!
答案 0 :(得分:1)
每个匹配的行都会更新一次,即使它与条件多次匹配。
但是,并没有特别说它是第一个始终使用的值,所以我不确定你是否能够可靠地依赖它。如果你编写子查询以便它只返回每个id_group_table
的冠军会更好。有很多SO问题显示如何编写这样的查询。