众所周知,左连接和右连接的含义是以哪一张表为准。

  左连接就是以左表为准,查出的结果中包含左表所有的记录,如果右表中没有与其对应的记录,那么那一行记录中B表部分的内容就全是NULL。

  

  

  现在有两个表,一个category表和goods表:

mysql> select * from category;
+----+---------+
| id | cate |
+----+---------+
| 1 | food |
| 2 | clothes |
| 3 | book |
| 4 | sport |
| 5 | music |
| 6 | video |
+----+---------+
6 rows in set (0.01 sec) mysql> select * from goods;
+----+---------+-------------------+
| id | cate_id | name |
+----+---------+-------------------+
| 0 | 5 | You Are Not Alone |
| 1 | 2 | T-shirt |
| 2 | 1 | water |
| 3 | 1 | rice |
| 4 | 3 | C++ primer |
| 5 | 4 | basketbal |
+----+---------+-------------------+
6 rows in set (0.00 sec)

  

  现在要查出每一种分类下的商品,那么可以很简单的使用左连接了:

mysql> select * from category
-> left join goods
-> on category.id = goods.cate_id
-> order by category.id;
+----+---------+------+---------+-------------------+
| id | cate | id | cate_id | name |
+----+---------+------+---------+-------------------+
| 1 | food | 2 | 1 | water |
| 1 | food | 3 | 1 | rice |
| 2 | clothes | 1 | 2 | T-shirt |
| 3 | book | 4 | 3 | C++ primer |
| 4 | sport | 5 | 4 | basketbal |
| 5 | music | 0 | 5 | You Are Not Alone |
| 6 | video | NULL | NULL | NULL |
+----+---------+------+---------+-------------------+
7 rows in set (0.01 sec)

  从上面的结果中很全就能看到video分类中没有商品。

  需求:只查询哪一种分类下面没有商品

  这个很好实现,可以用下面几个方法:

  1、使用not in

mysql> select * from category where id not in ( select cate_id from goods);
+----+-------+
| id | cate |
+----+-------+
| 6 | video |
+----+-------+
1 row in set (0.01 sec)

  2、仍旧使用左连接,只不过对于结果加一个where筛选

mysql> select * from category
-> left join goods
-> on category.id = goods.cate_id
-> where goods.id is NULL;
+----+-------+------+---------+------+
| id | cate | id | cate_id | name |
+----+-------+------+---------+------+
| 6 | video | NULL | NULL | NULL |
+----+-------+------+---------+------+
1 row in set (0.00 sec)

  

  至于为什么不适用not in,这是因为他不使用索引,如果数据量大的时候,效率并不高。

  同样,如果要显示和总表中匹配了记录,隐藏左表没有匹配到的记录,可以将后面的where goods.id is not NULL;

  同样,对于右连接来说也是一样的。

最新文章

  1. (转)SQL 优化原则
  2. SQL SERVER中用户定义标量函数(scalar user defined function)的性能问题
  3. Javascript事件模型系列(一)事件及事件的三种模型
  4. mac 下如何切换jdk的版本
  5. innodb内部的并发线程
  6. QCom MSM MDP显示驱动一些点的简记
  7. Realtek 8168 安装 VMware ESXi 提示没有驱动
  8. jdbcTemplate 获取数据表结构
  9. (五)Struts2 标签
  10. 关于js的callback回调函数的理解
  11. 在VS2012中使用GitHub
  12. 下载带有kali linux系统的VMware如何打开虚拟机?
  13. hdu-1686(kmp)
  14. opencv+python 自动绿帽机
  15. mafintosh/end-of-stream
  16. redis nginx session tomcat
  17. 查看虚拟机CENTOS7 的 IP 地址和命令
  18. python基础-类的封装
  19. CSU 1598 最长公共前缀 (简单KMP或者暴力)
  20. [BJOI2017]魔法咒语 --- AC自动机 + 矩阵优化

热门文章

  1. 关于Numba开源库(Python语法代码加速处理,看过一个例子,速度可提高6倍)
  2. JavaScript -- 时光流逝(七):js中的全局函数
  3. 分布式消息中间件rocketmq的原理与实践
  4. 12个 Linux 中 grep 命令的超级用法实例
  5. 两段锁协议(Two-Phase Locking――2PL)
  6. centos7下kubernetes(10。kubernetes-daemonset)
  7. Python入门学习:1.变量和简单的数据类型
  8. 100Mbps和100Mb/s有什么不同
  9. P1184 高手之在一起(字典树模板题,hash算法, map)
  10. 洛谷题解 P1031 【均分纸牌】