M
M
Mois2016-11-07 04:13:24
MySQL
Mois, 2016-11-07 04:13:24

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

But there is one feature! The second table (b) does not contain all the id values ​​that the first one (a) has. It is necessary that the answer would still be, at least only with the values ​​of the first table.
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    |
+--------+------------+---------+

And this query will return what I need: OK
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        |
+------------+---------+------------+-------------+

And such a request will not return anything at all: BAD
SELECT a.name, a.img, b.price, b.discount FROM table1 as a, table2 as b WHERE a.id=5 AND b.id = 5

And I would like something like this:
+------------+---------+------------+-------------+
| name       | img     | price      | discount    |
+------------+---------+------------+-------------+
| name5      | url5    | NULL       | NULL        |
+------------+---------+------------+-------------+

ANSWER:
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

1 answer(s)
D
Dmitry, 2016-11-07
@Mois

Goodnight.
Or try using join
ps About join and some more

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question