在具有引用主表上的主id的外键的两个表上使用内部联接

时间:2013-12-06 17:31:21

标签: mysql sql

假设我有以下表格:

BrandsTable

+-----------+--------------+------+-----+---------+-------+
| Field     | Type         | Null | Key | Default | Extra |
+-----------+--------------+------+-----+---------+-------+
| ID        | varchar(20)  | NO   | PRI | NULL    |       |
| CarBrand  | varchar(100) | NO   |     | NULL    |       |
| FuelType  | varchar(100) | NO   |     | NULL    |       |
+-----------+--------------+------+-----+---------+-------+

ModelsTable

+------------+--------------+------+-----+---------+-------+
| Field      | Type         | Null | Key | Default | Extra |
+------------+--------------+------+-----+---------+-------+
| ID         | int(2)       | NO   |     | NULL    |       |
| Model      | varchar(100) | NO   |     | NULL    |       |
| BrandID    | varchar(100) | NO   | MUL | NULL    |       |
| TopSpeed   | varchar(100) | NO   |     | NULL    |       |
+------------+--------------+------+-----+---------+-------+

以下是一些条目

+----+----------------+-------------------------+
| ID | CarBrand       | FuelType                |
+----+----------------+-------------------------+
| 0  | Ford           | Gasoline                |
| 1  | Chevy          | Gasoline                |
| 2  | Peterbilt      | Diesel                  |
| 3  | GMC            | Gasoline                |
| 4  | OshKosh        | Natural Gas             |
+----+----------------+-------------------------+

+----+---------------+---------+------------+
| ID | Model         | BrandID | TopSpeed   |
+----+---------------+---------+------------+
|  1 | F150          | 0       | 130MPH     |
|  2 | 1500          | 1       | 110MPH     |
|  3 | 389           | 2       | 70MPH      |
|  4 | 1500          | 3       | 110MPH     |
|  5 | Mustang       | 0       | 170MPH     |
|  6 | Cement Truck  | 4       | 65MPH      |
+----+---------------+---------+------------+

Models表中的BrandID列是Brand表的主键ID列的外键。如果您无法访问任何一列的值,该怎么办?我将如何编写一个SQL查询,该查询将使用INNER JOIN列出所有属于Ford的模型

1 个答案:

答案 0 :(得分:1)

没有访问ID,这意味着你只有我猜的模型名称.. 所以知道“福特”你可以得到这样的两个ids ......

select * from modelsTable Mod inner join brandsTable Bra
on Mod.id= ( select id from Bra where CarBrand='FORD')