2015-08-26 55 views
1

從表*我有兩個表:MySQL的選擇與特定鍵

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

在表格之間執行JOIN,並使用WHERE子句選擇所選的顏色。 – jarlh

回答

0
SELECT 
    car.name 
FROM 
    car 
    LEFT JOIN color ON car.colorId = color.id 
WHERE 
    color.name = 'Red' 

該查詢將返回紅色汽車的名稱。切記將顏色作爲字符串插入時要妥善轉義(使用mysql_real_escape_stringmysqli_real_escape_string)以防止SQL injection

+1

當WHERE子句在右手錶中需要非空值時,使用左連接沒有意義... –

2
SELECT car.Name 
     ,color.Name 
FROM Car 
INNER JOIN color ON Car.ColorId = Color.ID 
WHERE ColorID = ??? --<-- the color id you are looking for 
-1
select car.name 
from car,color 
where color.name = 'red' 
and color.id = car.colorId 


如果你想要檢索的汽車,是紅色的。

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; 
+0

非常感謝 - 現在看起來不錯。 –