S
S
Sergey Eremin2015-12-03 02:34:05
MySQL
Sergey Eremin, 2015-12-03 02:34:05

How to make SQL UNION if there is not full data in the tables?

I have never been a programmer, but fifteen years ago I once built a similar query ... I remember that I somehow applied UNIONfictitious fields like O AS FIELD... And I also remember that I spent three weeks (or maybe more) on it. And now the brains are completely rusted and I can’t even figure out where to start. And you need something like this:
There is a "TAR" TABLE:

id1 |  НАЗВАНИЕ_ТАРЫ
----+-------------------------
01  |  Ящик
02  |  Корзинка
03  |  Грузовик

There is a "LOAD" TABLE:
id2 |  НАЗВАНИЕ_ГРУЗА
----+------------------------
01  |  Огурцы
02  |  Молоко
03  |  Туалетная бумага

There is a "TABLE OF RELATIONSHIPS":
link1 |  link2    | КОЛИЧЕСТВО
------+-----------+--------------------
01    |  01       |  15 
01    |  02       |  2
02    |  01       |  4
02    |  03       |  2
03    |  01       |  100
03    |  02       |  60
03    |  03       |  500

And I want to get:
НАЗВАНИЕ_ТАРЫ  |  НАЗВАНИЕ_ГРУЗА    |  КОЛИЧЕСТВО
---------------+--------------------+----------------
Ящик           |  Огурцы            |  15
Ящик           |  Молоко            |  2
Ящик           |  Туалетная бумага  |  0
Корзинка       |  Огурцы            |  4
Корзинка       |  Молоко            |  0
Корзинка       |  Туалетная бумага  |  2
Грузовик       |  Огурцы            |  100
Грузовик       |  Молоко            |  60
Грузовик       |  Туалетная бумага  |  500

That is, you need to get 0for the field КОЛИЧЕСТВОin cases where the objects are not connected through ТАБЛИЦА СВЯЗЕЙ. How?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
sunrails, 2015-12-03
@Sergei_Erjemin

table_box - container
table_product - cargo
table_link - link

SELECT t1.name, t2.name, IFNULL(t3.qty, 0) as qty FROM table_box as t1 
INNER JOIN table_product as t2 
LEFT JOIN table_link as t3 ON (t3.link1 = t1.id1 AND t3.link2 = t2.id2);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question