2013-12-23 88 views
0

我有表report_business_likes与相关领域:如何根据mySql中的其他表更新字段值?

id, facebook_id, created_at, some_info 
-- ----------- ----------- ---------- 
1 123456789 '2013-12-23' blabla 

我有一个名为businesses,接着结构的其他表:

id, fb_id, data 
-- -----  ---- 
33 123456789 xxx 

我想在report_business_likesfacebook_idid从表businesses更换。

在我的情况下,结果应该是:

id, facebook_id, created_at, some_info 
-- ----------- ----------- ---------- 
1 33   '2013-12-23' blabla 

正如你可以看到我更换12345678933

我该如何做到这一点?

我想:

UPDATE `report_business_likes` SET facebook_id = BZ.id from 
    (select id from `businesses` where fb_id = 123456789) as BZ, 
    where facebook_id = 123456789 AND date(created_at) = '2013-12-23'; 

,但得到语法错误:

[SQL] /*SELECT * FROM `report_business_likes` where facebook_id = 123456789 AND date(created_at) = '2013-12-23';*/ 

UPDATE `report_business_likes` SET facebook_id = BZ from 
(select id from `businesses` where fb_id = 123456789) as BZ, 
where facebook_id = 123456789AND date(created_at) = '2013-12-23'; 
[Err] 1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'from 
(select id from `businesses` where fb_id = 123456789) as BZ,' at line 3 

请帮帮忙,

+0

表和列名中的报价。 – Sergi

+0

发布错误信息请 – Barranka

+0

@Barranka我发布了一个错误,谢谢 – snaggs

回答

4
UPDATE report_business_likes 
    SET facebook_id = (select id 
         from businesses 
         where facebook_id = 123456789) 
WHERE facebook_id = 123456789 AND date(created_at) = '2013-12-23' 

OR

UPDATE RBL 
SET RBL.facebook_id = B.id 
FROM report_business_likes RBL INNER JOIN businesses B 
ON RBL.facebook_id = B.facebook_id 
2
UPDATE report_business_likes r JOIN businesses b ON r.facebook_id=b.fb_id 
SET r.facebook_id=b.id 
1

您正在尝试混合语法。为update正确的语法是:

update `Your table` 
set `Field in yourTable` = `value or expression` 
where `Conditions to filter the data in your table` 

有一个在update语法为from条款没有地方。

当然,如果你想用子查询的结果更新你的字段,你可以(见M.Ali的答案)。请致电reference manual

1

您可以通过以下尝试:

Update set sb.facebook_id=b.id from 
report_business _likes rb join business b on r.facebook_id=b.fb_id 
相关问题