在mysql中如果要同时查找多表并且多表时间有关系查询我们有很多种方法来实现,现在我们只介绍利用mysql left join来实现。
具体操作
mysql支持select和某些update和delete情况下的join语法,具体语法上的细节有:
table_references:
table_reference [, table_reference] …
table_reference:
table_factor
| join_table
table_factor:
tbl_name [[as] alias]
[{use|ignore|force} index (key_list)]
| ( table_references )
| { oj table_reference left outer join table_reference
on conditional_expr }
join_table:
table_reference [inner | cross] join table_factor [join_condition]
| table_reference straight_join table_factor
| table_reference straight_join table_factor on condition
| table_reference left [outer] join table_reference join_condition
| table_reference natural [left [outer]] join table_factor
| table_reference right [outer] join table_reference join_condition
| table_reference natural [right [outer]] join table_factor
join_condition:
on conditional_expr | using (column_list)
除了常用的两个表连接之外,sql(mysql) join 语法还支持多表连接。多表连接基本语法如下:
... from table1 inner|left|right join table2 on condition inner|left|right join table3 on condition ...
join 多表连接实现了从多个表中获取相关数据,下面是三个原始数据表:
article 文章表: aid title content uid tid
1 文章1 文章1正文内容... 1 1
2 文章2 文章2正文内容... 1 2
3 文章3 文章3正文内容... 2 1
5 文章5 文章5正文内容... 4 1
user 用户表: uid username email
1 admin admin@5idev.com
2 小明 xiao@163.com
3 jack jack@gmail.com
type 文章类型表: tid typename
1 普通文章
2 精华文章
3 草稿
代码如下 复制代码
select * from t1 left join (t2, t3, t4) on (t2.a=t1.a and t3.b=t1.b and t4.c=t1.c)