O
O
Old Odessa2018-03-23 18:30:13
SQL
Old Odessa, 2018-03-23 18:30:13

How beautifully (correctly) to write a request for the next task (under the cut)?

There are two tables:
Table_A:
______________________
id_class id_subclass
1 1.1
1 1.2
2 2.1
______________________
Table_B:
______________________
Id Parameter
1 A
2 B
1.1 C
1.2 D
2.1 E
_______________________
You need to get something like this:
Id_class Parameter Id_subclass Parameter
1 A 1.1 C
1 A 1.2 D
2 B 2.1 E
Here is my solution:

WITH T1 AS 
(SELECT Table_A.Id_class, Table_B.Parameter AS Par_1 FROM Table_A JOIN Table_B ON Table_A.Id_class = Table_B.Id), 
T2 AS 
(SELECT Table_A.Id_subclass, Table_A.Id_class, Table_B.Parameter AS Par_2 FROM Table_A JOIN Table_B ON Table_A.Id_subclass = Table_B.Id)

SELECT DISTINCT T1.Id_class, Par_1, T2.Id_subclass, Par_2 FROM 
T1 LEFT JOIN T2
ON T1.Id_class = T2.Id_class;

Can you suggest something more concise?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Rsa97, 2018-03-23
@Rsa97

SELECT `a`.`id_class`, `pc`.`Parameter` AS `class_parameter`,
       `a`.`id_subclass`, `ps`.`Parameter` AS `subclass_parameter`
  FROM `Table_A` as `a`
  JOIN `Table_B` as `pc` ON `pc`.`id` = `a`.`id_class`
  JOIN `Table_B` as `ps` ON `ps`.`id` = `a`.`id_subclass`

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question