简体   繁体   中英

MySQL query get name and color by 3rd table

I know it is something pretty simple for you but i am really confused.I got 3 tables

**users**
| id | username |
--1------pesho---
--2------gosho---

**colors**
| id | color |
---1-----red---
---2---purple--

**user_color**
| id | user_id | color_id |
--1------1-----------2-----
--2------2-----------1-----

How should i construct my query to get the user pesho 's favorite color, which is purple . In the 3rd table are the relations. I tried whit SELECT 'users'.'username', 'colors'.'color' FROM 'users' LEFT JOIN 'user_color' ON 'users'.'id'='user_color'.'user_id' WHERE 'user_color'.'user_id'=1 but this also gives me an error #1054 - Unknown column 'colors.color' in 'field list' . How should i construct it to take the name of pesho and his favorite color - purple. It is real mess in my head! Thank you in advance!

This will do, what you want

Select color from colors 
where colors.id in (select color_id from user_color 
where user_id in(select id from users 
where username="pesho"))

You are not joining the user_color table to the colors table in your SELECT query. You need to be doing:

SELECT `users`.`username`, `colors`.`color` FROM `users` 
    LEFT JOIN `user_color` ON `users`.`id`=`user_color`.`user_id` 
    LEFT JOIN `colors` on `colors`.`id` = `user_color`.`color_id`
    WHERE `user_color`.`user_id`=1;

This is very basic stuff, covered in any beginner's manual or online tutorial. I'm only answering because the other answers provided so far are misleading.

DROP TABLE IF EXISTS users;

CREATE TABLE users
(id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
,username VARCHAR(12) NOT NULL
);

INSERT INTO users VALUES
(1,'pesho'),
(2,'gosho');


DROP TABLE IF EXISTS colors;

CREATE TABLE colors
(id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
,color VARCHAR(12) NOT NULL
);


INSERT INTO colors VALUES
(1,'red'),
(2,'purple');

DROP TABLE IF EXISTS user_color;

CREATE TABLE user_color
(user_id INT NOT NULL
,color_id INT NOT NULL
);

INSERT INTO user_color VALUES
(1,2),
(2,1);

SELECT u.*
     , c.*
  FROM users u
  LEFT
  JOIN user_color uc
    ON uc.user_id = u.id
  LEFT
  JOIN colors c
    ON c.id = uc.color_id
 WHERE u.id = 1;
+----+----------+------+--------+
| id | username | id   | color  |
+----+----------+------+--------+
|  1 | pesho    |    2 | purple |
+----+----------+------+--------+

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM