简体   繁体   中英

How to create SQL-Query to update data in tables?

I'm trying to update data in my table.

I have two tables, t1 and t2

T1 第一张桌子

T2 第二张桌子

I'm want to do, that if t1 have id_avito = null and all_usl_name = %usl_name1% and all_tel = %tel1% , and t2 have id != null , usl_name = %usl_name1% and tel = %tel1%

For example, t1 after execute query must to look like that更新 t1

update people.t1, people.t2
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 
where id_avito != people.t2.id
and all_tel= people.t2.tel 
and all_usl_type = people.t2.usl_type

I try to do like this, but it is not working

UPD

EXAMPLE: tables . Table before update, after update, and second table

Try with update join also you need to use like operator where you are searching with string

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 

Please try this.

For 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%'

FOR 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%'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM