如何从多个表中查询sql数据

时间:2015-12-17 04:39:14

标签: mysql database

如何查询多个表格中的数据 例如:

我想获取main_id 1的所有信息。
基本上是单个查询中的品牌,类别,型号和SN。

MAIN_TABLE

id brand category model sn
1....1....2........1....1
2....2....1........3....2
3....2....4........5....3

brand_table

id....name....main_fk
1....Apple....1
2....Sony.....3

Category_table

id....name.........main_fk
1....Electronics...1
2....Furniture.....4

Model_table

id....name....main_fk
1....Iphone5..1
2....GoPro3...2

SN_table

id....name....main_fk
1....SN1......1
2....SN2......2

1 个答案:

答案 0 :(得分:1)

查询:

SELECT bt.name as brand, ct.name as category, mt.name as model, sn.name as sn
FROM main_tbl as maint
INNER JOIN brand_table as bt ON bt.main_fk = maint.id
INNER JOIN category_table as ct ON ct.main_fk = maint.id
INNER JOIN model_table as mt ON mt.main_fk = maint.id
INNER JOIN SN_table as sn ON sn.main_fk = maint.id

有关INNER JOIN的更多信息:INNER JOIN