0

I have 2 tables:

car

ID    Desc
1     BMW
2     Audi

user

ID   Name    ID_car1     ID_car2
1    Jack       1           2

Data View

ID    Name   ID_car1   Desc_car1    ID_car2    Desc_car2
1     Jack      1          BMW        2           Audi

How to query to show desc_car1 and desc_car2 on Data view?

Drajad
  • 53
  • 7

2 Answers2

1

Ideally there should be a third junction table which persists the relationship between users and cars. If you want a literal query to generate the above output in the absence of such a table, then we would have to use a cross join between car and user, because no other relations exist:

SELECT
    u.ID,
    u.Name,
    MAX(CASE WHEN c.ID = 1 THEN c.ID END) AS ID_car1,
    MAX(CASE WHEN c.ID = 1 THEN c.`Desc` END) AS Desc_car1,
    MAX(CASE WHEN c.ID = 2 THEN c.ID END) AS ID_car2,
    MAX(CASE WHEN c.ID = 2 THEN c.`Desc` END) AS Desc_car2
FROM car c
CROSS JOIN user u
GROUP BY
    u.ID,
    u.Name;

enter image description here

Demo

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
0

Using your recent information, we can get the Data View using a query, like so:

select u.ID, u.Name,
  u.ID_car1, c1.Desc Desc_car1,
  u.ID_car2, c2.Desc Desc_car2
from user u
  join car c1 on u.ID_car1=c1.ID
  join car c2 on u.ID_car2=c2.ID;
Junjie
  • 491
  • 1
  • 6
  • 13