简体   繁体   中英

SQL query add new column if two existing columns matches and add value from another column

Table 1 columns are (current state)

=======================================================
record_id |  ad_id | gender | gender_view | time_entry
=======================================================
1         |   1    |  male  |     45      | 1557072000
2         |   1    | female |     88      | 1557072000

Table 2 columns are (current state)

=====================
ad_id | submitted_by
=====================
1     |   1

After matching the ad_id of table 1 and table 2 , table 1 will have new column submitted_by . The new column submitted_by in table 1 will take submitted_by value from table 2.

Table 1 columns (expected state)

====================================================================
record_id |  ad_id | gender | gender_view | time_entry | submitted_by 
====================================================================
1         |   1    |  male  |     45      | 1557072000 |   1
2         |   1    | female |     88      | 1557072000 |   1

A simple LEFT JOIN with ON T2.ad_id = T1.ad_id , will return your expected result:

SELECT T1.record_id,
       T1.ad_id,
       T1.gender,
       T1.gender_view,
       T1.time_entry
       COALESCE(T2.submitted_by, 0) submitted_by
FROM Table1 T1
LEFT JOIN Table2 T2 ON T2.ad_id = T1.ad_id
select t1.*,t2.submitted_by 
from table1 t1 
inner join table2 t2 on t1.ad_id = t2.ad_id

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