SQL查询具有更深的关系

时间:2013-07-02 13:56:09

标签: mysql sql

Table: user
Columns
- id
- username
- full_name

Table: pet
Columns
- id
- pet_name
- color_id

Table: pet_color
Columns
- id
- color

Table: results
Columns
- id
- user_id_1
- user_id_2
- user_id_3
- pet_id
- date
- some_text

此:

SELECT A.id, B.full_name, C.full_name, D.full_name, E.pet_name, A.date, A.some_text
FROM RESULTS AS A 
LEFT OUTER JOIN USER AS B ON A.USER_ID1 = B.ID
LEFT OUTER JOIN USER AS C ON A.USER_ID2 = C.ID
LEFT OUTER JOIN USER AS D ON A.USER_ID3 = D.ID
LEFT OUTER JOIN PET AS E ON A.PET_ID = E.ID

除了' pet_color.color'之外,几乎可以给我任何我想要的东西,但是我无法弄明白我应该在查询中添加什么来获得它。

3 个答案:

答案 0 :(得分:0)

SELECT A.id, B.full_name, C.full_name, D.full_name, E.pet_name, A.date, A.some_text, pc.color
FROM RESULTS AS A 
LEFT OUTER JOIN USER AS B ON A.USER_ID1 = B.ID
LEFT OUTER JOIN USER AS C ON A.USER_ID2 = C.ID
LEFT OUTER JOIN USER AS D ON A.USER_ID3 = D.ID
LEFT OUTER JOIN PET AS E ON A.PET_ID = E.ID
LEFT OUTER JOIN PET_COLOR PC on E.color_id = pc.id

答案 1 :(得分:0)

SELECT A.id, B.full_name, C.full_name, D.full_name, E.pet_name, A.date, A.some_text, PC.color
FROM RESULTS AS A 
LEFT OUTER JOIN USER AS B ON A.USER_ID1 = B.ID
LEFT OUTER JOIN USER AS C ON A.USER_ID2 = C.ID
LEFT OUTER JOIN USER AS D ON A.USER_ID3 = D.ID
LEFT OUTER JOIN PET AS E ON A.PET_ID = E.ID
LEFT OUTER JOIN PET_COLOR PC ON E.COLOR_ID = PC.ID

答案 2 :(得分:0)

未尝试,但这应该有效

SELECT A.id, B.full_name, C.full_name, D.full_name, E.pet_name, A.date, A.some_text
FROM RESULTS AS A 
LEFT OUTER JOIN USER AS B ON A.USER_ID1 = B.ID
LEFT OUTER JOIN USER AS C ON A.USER_ID2 = C.ID
LEFT OUTER JOIN USER AS D ON A.USER_ID3 = D.ID
LEFT OUTER JOIN PET AS E ON A.PET_ID = E.ID
INNER JOIN PET_COLOR PC ON PC.ID = E.COLOR_ID