MySQL从具有特定键的表中选择*

时间:2015-08-26 13:11:29

标签: mysql sql select

我有两张桌子:

CREATE TABLE IF NOT EXISTS color(
    id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(255) NOT NULL) DEFAULT CHARSET=utf8 COLLATE=utf8_bin;'

CREATE TABLE IF NOT EXISTS car(
    id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
    colorId INT UNSIGNED NOT NULL,
    name VARCHAR(255) NOT NULL,
    FOREIGN KEY (colorId) REFERENCES color(id)) DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

如何从"颜色"中选择具有指定colorId和颜色名称的汽车名称?表?

2 个答案:

答案 0 :(得分:0)

这里是带有示例的查询。你可以创建自己的

CREATE TABLE IF NOT EXISTS color(
    id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(255) NOT NULL) DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

CREATE TABLE IF NOT EXISTS car(
    id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
    colorId INT UNSIGNED NOT NULL,
    name VARCHAR(255) NOT NULL,
    FOREIGN KEY (colorId) REFERENCES color(id)) DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

insert into color(name)
values('RED'),('BLUE'),('GREEn'),('YELLOW'),('PINK'),('ORANGE'),('WHITE'),('BLACK');

 insert into car(colorid, name)
 values(1,'BMW'),
(1,'AUDI'),
(1,'ASTON MARTIN'),
(4,'FERRARI'),
(3,'MUSTANG'),
(6,'SANTA FIEAA');

join Query..

select c.name, c.colorid, cl.name
from car c
join color cl on c.colorID = cl.id;

答案 1 :(得分:-1)

select car.name
 from car,color 
where color.name = 'red' 
and color.id = car.colorId


如果你想检索红色的汽车。