L
L
leni_m2018-02-20 16:16:10
MySQL
leni_m, 2018-02-20 16:16:10

How to write a MySQL query?

There are 2 tables

table1
id | data
...
-----------------------
table2
id | data | table1_id
...

The query "SELECT * from table1" will output
id | data
1  | bla-bla-bla
2  | bla-bla-bla

And I need to add 1 more column to the output, which shows whether the second table has a "table1_id" field equal to the "id" field from the first table, and if not, then for example it would display NULL
I.e. for example if we have the following tables
table1
id | data
1  | bla-bla-bla
2  | bla-bla-bla
3  | bla-bla-bla
...
--------------------
table2
id | data | table1_id
1  | ...  | 2
2  | ...  | 3
...
--------------------

Then the query would output
id | data           | new_stolbik
1  | bla-bla-bla    | NULL
2  | bla-bla-bla    | 1
3  | bla-bla-bla    | 2

Those. if there is no match, then NULL, and if there is, then the id of this row from the second table.
Please tell me what is the request?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Fedorov, 2018-02-20
@leni_m

SELECT 
    table1.*, 
    table2.table1_id as new_stolbik
FROM table1
LEFT JOIN table2 ON table2.table1_id = table1.id

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question