手机
当前位置:查字典教程网 >编程开发 >mysql数据库 >MySQL在右表数据不唯一的情况下使用left join的方法
MySQL在右表数据不唯一的情况下使用left join的方法
摘要:1.leftjoin基本用法mysqlleftjoin语句格式ALEFTJOINBON条件表达式leftjoin是以A表为基础,A表即左表,...

1.left join 基本用法

mysql left join 语句格式

A LEFT JOIN B ON 条件表达式

left join 是以A表为基础,A表即左表,B表即右表。

左表(A)的记录会全部显示,而右表(B)只会显示符合条件表达式的记录,如果在右表(B)中没有符合条件的记录,则记录不足的地方为NULL。

例如:news 与 news_category表的结构如下,news表的category_id与news_category表的id是对应关系。

news 表

MySQL在右表数据不唯一的情况下使用left join的方法1

news_category 表

MySQL在右表数据不唯一的情况下使用left join的方法2

显示news表记录,并显示news的category名称,查询语句如下

select a.id,a.title,b.name as category_name,a.content,a.addtime,a.lastmodify from news as a left join news_category as b on a.category_id = b.id;

查询结果如下:

MySQL在右表数据不唯一的情况下使用left join的方法3

因 news_category 表没有id=4的记录,因此news 表中category_id=4的记录的category_name=NULL

使用left join, A表与B表所显示的记录数为 1:1 或 1:0,A表的所有记录都会显示,B表只显示符合条件的记录。

2.left join 右表数据不唯一解决方法

但如果B表符合条件的记录数大于1条,就会出现1:n的情况,这样left join后的结果,记录数会多于A表的记录数。

例如:member与member_login_log表的结构如下,member记录会员信息,member_login_log记录会员每日的登入记录。member表的id与member_login_log表的uid是对应关系。

member 表

MySQL在右表数据不唯一的情况下使用left join的方法4

member_login_log 表

MySQL在右表数据不唯一的情况下使用left join的方法5

查询member用户的资料及最后登入日期:

如果直接使用left join

select a.id, a.username, b.logindate from member as a left join member_login_log as b on a.id = b.uid;

因member_login_log符合条件的记录比member表多(a.id = b.uid),所以最后得出的记录为:

MySQL在右表数据不唯一的情况下使用left join的方法6

但这并不是我们要的结果,因此这种情况需要保证B表的符合条件的记录是空或唯一,我们可以使用group by来实现。

select a.id, a.username, b.logindate from member as a left join (select uid, max(logindate) as logindate from member_login_log group by uid) as b on a.id = b.uid;

MySQL在右表数据不唯一的情况下使用left join的方法7

总结:使用left join的两个表,最好是1:1 或 1:0的关系,这样可以保证A表的记录全部显示,B表显示符合条件的记录。

如果B表符合条件的记录不唯一,就需要检查表设计是否合理了。

【MySQL在右表数据不唯一的情况下使用left join的方法】相关文章:

在MySQL数据库中使用C执行SQL语句的方法

在MySQL数据库中复位根用户的密码的方法

在MySQL中用正则表达式替换数据库中的内容的方法

MySQL动态创建表,数据分表的存储过程

虚拟主机MySQL数据库的备份与还原的方法

Mysql 数据库更新错误的解决方法

MySQL数据库索引使用方法

MySQL单表多关键字模糊查询的实现方法

MySQL replace函数替换字符串语句的用法

MySQL数据库中删除重复记录的方法总结[推荐]

精品推荐
分类导航