在数据库中所有数据库都是支持多表联合查询了,下面我来介绍利用left join在mysql中实现多表联合查询,有需要的朋友可参考
left 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 }
例:
代码如下 复制代码
mysql> create table `product` (
`id` int(10) unsigned not null auto_increment,
`amount` int(10) unsigned default null,
primary key (`id`)
) engine=myisam auto_increment=5 default charset=latin1
mysql> create table `product_details` (
`id` int(10) unsigned not null,
`weight` int(10) unsigned default null,
`exist` int(10) unsigned default null,
primary key (`id`)
) engine=myisam default charset=latin1
mysql> insert into product (id,amount)
values (1,100),(2,200),(3,300),(4,400);
query ok, 4 rows affected (0.00 sec)
records: 4 duplicates: 0 warnings: 0
mysql> insert into product_details (id,weight,exist)
values (2,22,0),(4,44,1),(5,55,0),(6,66,1);
query ok, 4 rows affected (0.00 sec)
records: 4 duplicates: 0 warnings: 0
查询
代码如下 复制代码
mysql> select * from product left join product_details
on (product.id = product_details.id)
and product.amount=200;
+----+--------+------+--------+-------+
| id | amount | id | weight | exist |
+----+--------+------+--------+-------+
| 1 | 100 | null | null | null |
| 2 | 200 | 2 | 22 | 0 |
| 3 | 300 | null | null | null |
| 4 | 400 | null | null | null |
+----+--------+------+--------+-------+
4 rows in set (0.01 sec)
超级简单吧,那么有朋友问我怎么在mysql中实现多表关联数据同时删除
category中的id(栏目编号)字段作为该表的主键(primary key).唯一标识了一个栏目的信息。
news 中的id字段作为该表的主键(primary key).唯一标识了一个栏目的信息。
category_id(栏目编号)字段与category表的id字段相关联。
1.sql删除语句
代码如下 复制代码
delete category,news from category left join news on category.id = news.category_id