mysql左右关联 内关联及having用法举例

发布时间:2020-08-30编辑:脚本学堂
为大家举一些mysql左右关联、内关联及having子句应用的例子,供大家学习参考。

以下示例用到的二张表:
user,字段,user_id,email,name
deal,字段deal_id,user_id,deal_name
对应关系,user.user_id = deal.user_id,

--左关联的例子:
select u.*,d.* from user as u left join deal as d on d.user_id = u.user_id;
--右关联的例子:
select u.*,d.* from user as u right join deal as d on d.user_id = u.user_id;
--内关联,其中inner可不写,
select u.* d.* from user as u innerjoin deal as d on d.user_id = u.user_id;

--左关联连写,加上第三个表,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等),同理右关联.
内关联,也就是自然关联对主表的限制就是附表中存在值,才显示数据.所以得到的结论是,左关联适合列表,内关联适合取值.
说说having的用法,having对结果集进行第二次筛选,相信一句话就够了.举个例子吧,查询多次用同一个email注册的用户:

select count(email) as e,username group by email having e>=2

其中group by对数据进行分组.mysql中没有全关联.