有关mysql左右关联与内关联的sql语句例子,左关联以左边这张表为主表,右边的为附表得到的数据对左表不加限制(在没有限制的条件下,比如没有where没有having等),同理右关联。
mysql左右关联与内关联的例子。
有如下二张表:
user,字段,user_id,email,name
deal,字段deal_id,user_id,deal_name
对应关系,user.user_id = deal.user_id,
1、左关联:
select u.*,d.* from user as u left join deal as d on d.user_id = u.user_id;
2、右关联:
select u.*,d.* from user as u right join deal as d on d.user_id = u.user_id;
3、内关联,其中inner可不写,
select u.* d.* from user as u innerjoin deal as d on d.user_id = u.user_id;
4、左关联连写,加上第三个表,shop,字段,shop_id,user_id,shop_name
select u.*,d.*,s.* from user as u left join deal as d on d.user_id = u.user_id left join shop as s on s.user_id = u.user_id;
多表多个连写,同理右关联和内关联,内关联跟普通的自然关联是一样的,上面那一句跟下面这句得到的结果是相同的:
select u.* d.* from user as u,deal as d where d.user_id = u.user_id;
区别:
左关联,以左边这张表为主表,右边的为附表,得到的数据对左表不加限制(当然,在没有限制的条件下,比如没有where没有having等),同理右关联.
内关联,也就是自然关联对主表的限制就是附表中存在值,才显示数据.所以得到的结论是,左关联适合列表,内关联适合取值.