0

I have this two tables:

Main:

id | name | hair_color | eye_color
1  | a    | 1          | 2
2  | b    | 1          | 3
3  | c    | 4          | 3

Items:

id | name 
1  | black
2  | blue
3  | green
4  | blonde

I want to select one row from the Main table but replace the hair_color and eye_color ids by theirs name that fits by the Items table.

I mean, for row number 1 in Main table, I want to get this details:

$res = array(
           id=>1,
           name=>'a',
           hair_color=>'black',
           eye_color=>'blue');

I tried this incorrect mysql query:

SELECT `main`.`id`, `main`.`name`, `items`.`name` as `hair_color`, `items`.`name` as `eye_color`
FROM `main`
LEFT JOIN `items` ON `main`.`hair_color` = `items`.`id
LEFT JOIN `items` ON `main`.`eye_color` = `items`.`id
WHERE `main`.`id` = 1

I know that this query is incorrect, but I don't know how to do this right.

Any idea?

Thanks

EDIT:

Thanks all!

4

2 回答 2

0

你很亲密,但你需要别名。

就像是

SELECT `main`.`id`, 
       `main`.`name`, 
       h.`name` as `hair_color`, 
       e.`name` as `eye_color`
FROM `main`
LEFT JOIN `items` h ON `main`.`hair_color` = h.id
LEFT JOIN `items` e ON `main`.`eye_color` = e.id
WHERE `main`.`id` = 1

SQL 小提琴演示

于 2013-09-05T13:55:28.610 回答
0

你只需要给你的items表起别名:

SELECT `main`.`id`, `main`.`name`,
       hi.`name` as `hair_color`, ei.`name` as `eye_color`
FROM `main`
LEFT JOIN `items` hi ON `main`.`hair_color` = hi.`id`
LEFT JOIN `items` ei ON `main`.`eye_color` = ei.`id`
于 2013-09-05T13:55:08.640 回答