Answer the question
In order to leave comments, you need to log in
How to make a selection from two tables by id, so that if there is no id in the second base, there would still be an answer?
There are two tables, you need to display some table values by id.
Here is the code that does exactly what you need.
SELECT a.name, a.img, b.price, b.discount FROM table1 as a, table2 as b WHERE a.id=40 AND b.id = 40
table1 table2
+--------+------------+---------+ +--------+------------+-------------+
| id | name | img | | id | price | discount |
+--------+------------+---------+ +--------+------------+-------------+
| 1 | name1 | url1 | | 1 | 123 | 9658 |
| 2 | name2 | url2 | | 2 | 78954 | 5322 |
| 3 | name3 | url3 | | 3 | 8562 | 9873 |
| 4 | name4 | url4 | | 4 | 9648 | 6544 |
| 5 | name5 | url5 | +--------+------------+-------------+
| 6 | name6 | url6 |
+--------+------------+---------+
SELECT a.name, a.img, b.price, b.discount FROM table1 as a, table2 as b WHERE a.id=2 AND b.id = 2
+------------+---------+------------+-------------+
| name | img | price | discount |
+------------+---------+------------+-------------+
| name2 | url2 | 78954 | 5322 |
+------------+---------+------------+-------------+
SELECT a.name, a.img, b.price, b.discount FROM table1 as a, table2 as b WHERE a.id=5 AND b.id = 5
+------------+---------+------------+-------------+
| name | img | price | discount |
+------------+---------+------------+-------------+
| name5 | url5 | NULL | NULL |
+------------+---------+------------+-------------+
SELECT a.name, a.img, b.price, b.discount FROM table1
LEFT OUTER JOIN table2
ON table1.id = table2.id
WHERE table1.id = 5
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question