简体   繁体   中英

Select data from two tables with LEFT JOIN

How to select all data from first table and if in second table row1 == row1 in first table then I need to insert rows from second table to result with LEFT JOIN.

first_table:

id    row1     some_data
1     2        test
2     3        test2

second_table:

id    row1    some_data
1     4       test
2     2       test2

Needed result is:

id   row1   some_data   id     row1   some_data
1    2      test        2      2      test2
2    3      test2       NULL   NULL   NULL

Query:

SELECT * 
FROM `first_table` AS c 
LEFT JOIN `second_table` AS s ON `c`.`row1` = `s`.`row1`

I am sorry for my bad English and thanks in advance.

this is how we can put left join

SELECT *
FROM first_table As c
LEFT JOIN second_table AS o ON c.row1 = o.row1

you can learn more about left join here .

The following LEFT OUTER JOIN should give the desired result. It is important use an alias tables (t1, t2) to designate.

SELECT t1.id, t1.row1, t1.some_data, t2.id, t2.row1, t2.some_data
  FROM first_table t1
  LEFT JOIN second_table t2
    ON t1.row1 = t2.row2
ORDER BY t1.id; 

Try this:

SELECT f.*,s.id,s.row1,s.some_data
FROM first_table As f
LEFT JOIN second_table AS s ON f.row1 = s.row1

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