web*_*ers 6 php mysql database
我有一个UPDATE查询,我明确地引用了数据库,但MySQL仍然抱怨消息:ERROR 1046 (3D000): No database selected.
其他类似结构的查询,但使用INSERT工作正常.其他只执行SELECT的查询也运行正常.
要在测试用例中重复该问题,请尝试运行以下查询:
create table test.object1 (
id_object1 int unsigned not null auto_increment,
total int,
weight int,
dt datetime,
primary key (id_object1)
) engine=InnoDB;
create table test.object2 (
id_object2 int unsigned not null auto_increment,
primary key (id_object2)
) engine=InnoDB;
create table test.score (
id_object1 int unsigned not null,
id_object2 int unsigned not null,
dt datetime,
score float,
primary key (id_object1, id_object2),
constraint fk_object1 foreign key (id_object1) references object1 (id_object1),
constraint fk_object2 foreign key (id_object2) references object2 (id_object2)
) engine=InnoDB;
insert into test.object1 (id_object1, total, weight, dt) values (1, 0, 0, '2012-01-01 00:00:00');
insert into test.object1 (id_object1, total, weight, dt) values (2, 0, 0, '2012-01-02 00:00:00');
insert into test.object2 (id_object2) values (1);
insert into test.score (id_object1, id_object2, dt, score) values (1, 1, '2012-01-03 00:00:00', 10);
insert into test.score (id_object1, id_object2, dt, score) values (2, 1, '2012-01-04 00:00:00', 8);
update test.object1 p
join (
select ur.id_object1, sum(ur.score * ur.weight) as total, count(*) as weight
from (
select lur.*
from (
select s.id_object1, s.id_object2, s.dt, s.score, 1 as weight
from test.score as s
join test.object1 as o1 using(id_object1)
where s.dt > o1.dt
order by s.id_object1, s.id_object2, s.dt desc
) as lur
group by lur.id_object2, lur.id_object1, date(lur.dt)
order by lur.id_object1, lur.id_object2
) as ur
group by ur.id_object1
) as r using(id_object1)
set
p.total = p.total + r.total,
p.weight = p.weight + r.weight,
p.dt = now();
Run Code Online (Sandbox Code Playgroud)
注意:我正在从PHP环境运行这些查询,并且我没有明确地使用mysql_select_db('test'),因为我不喜欢并且没有其他(很多!)查询需要它.我确信使用mysql_select_db可以解决我的问题,但我想知道为什么这个特定的查询不起作用.
为了比较:如果你运行这个更简单的查询,也没有使用mysql_select_db,一切正常:
update test.object1 set total=1, weight=1, dt=now() where id_object1=1;
Run Code Online (Sandbox Code Playgroud)
我搜索无济于事.我发现的唯一一个接近的是这个错误报告:http://bugs.mysql.com/bug.php?id = 28551,特别是那个最后(未答复)的消息......
您的字段命名不正确,但即使您更正它们,这也是一个错误,MySQL如果您没有默认数据库,则不会让您这样做。
update test.object1 p
join (
select ur.id_object1, sum(ur.score * ur.weight) as total, count(*) as weight
from (
select lur.*
from (
select s.id_object1, s.id_object2, s.dt, s.score, 1 as weight
from test.score as s
join test.object1 as o1
using (id_object1)
where s.dt > o1.dt
order by
s.id_object1, s.id_object2, s.dt desc
) as lur
group by
lur.id_object1, lur.id_object1, date(lur.dt)
order by
lur.id_object1, lur.id_object1
) as ur
group by ur.id_object1
) as r
USING (id_object1)
SET p.total = p.total + r.total,
p.weight = p.weight + r.weight,
p.dt = now();
Run Code Online (Sandbox Code Playgroud)
该问题特定于UPDATE双嵌套查询且没有默认数据库(SELECT或单嵌套查询或默认数据库工作正常)