如何创建SQL查询以更新表中的数据?

时间:2019-03-25 05:58:03

标签: mysql sql

我正在尝试更新表中的数据。

我有两个表t1和t2

T1 first table

T2 second table

我想做的是,如果t1具有id_avito = nullall_usl_name = %usl_name1%all_tel = %tel1%,而t2具有id != nullusl_name = %usl_name1%和{{1 }}

例如,执行查询后的t1必须看起来像updated t1

tel = %tel1%

我尝试这样做,但是不起作用

UPD

示例:tables。更新前,更新后和第二张表的表

2 个答案:

答案 0 :(得分:1)

尝试使用更新连接,还需要在要搜索字符串的地方使用like运算符

update people.t1 a  
join people.t2 on id_avito != people.t2.id
and all_tel= people.t2.tel 
and all_usl_type = people.t2.usl_type
set 
    id_avito = people.t2.id, 
    lnk_avito = people.t2.link, 
    all_price = people.t2.price,
    all_date = people.t2.date, 
    all_adr = people.t2.adr,
    all_usl_name = people.t2.usl_name 

答案 1 :(得分:0)

请尝试这个。

对于SQL

 UPDATE A
 SET 
    A.id_avito = B.id, 
    A.lnk_avito = B.link, 
    A.all_price = B.price,
    A.all_date = B.date, 
    A.all_adr = B.adr,
    A.all_usl_name = B.usl_name 
 FROM 
    people.t1  A
    INNER JOIN people.t2 B
    ON A.id_avito != B.id
    AND A.all_tel= B.tel 
    AND A.all_usl_type =B.usl_type 
where ISNULL(A.id_avito,'') ='' and A.all_usl_name like '%usl_name1%' and A.all_tel like '%tel1%' and B.id is not null and B.usl_name like '%usl_name1%' and B.tel like '%tel1%'

对于MYSQL

UPDATE people.t1 a  
INNER JOIN people.t2 B
    ON A.id_avito != B.id
    AND A.all_tel= B.tel 
    AND A.all_usl_type =B.usl_type
   SET 
        A.id_avito = B.id, 
        A.lnk_avito = B.link, 
        A.all_price = B.price,
        A.all_date = B.date, 
        A.all_adr = B.adr,
        A.all_usl_name = B.usl_name 
where IFNULL(A.id_avito,'') = ''  and A.all_usl_name like '%usl_name1%' and A.all_tel like '%tel1%' and IFNULL(B.id,0) <> 0 and B.usl_name like '%usl_name1%' and B.tel like '%tel1%'