SQL中on和where的区别

SQL中on和where的区别

on 和 where 的区别主要在join中体现。

  • inner join :无区别
  • left join、right join:
    on条件在生成临时表中使用,无论on后的条件是否为真,都会返回记录。
    where是指在生成临时表之后,再对临时表进行过滤。

on:“id=4”的记录返回,且有“count = NULL”的记录

mysql> select w.id, w.name, w.url, a.count from Websites as w left join access_log as a on w.id = a.site_id and w.id != 4 and a.site_id != 4;
+----+----------+---------------------------+-------+
| id | name     | url                       | count |
+----+----------+---------------------------+-------+
|  1 | Google   | https://www.google.cm/    |    45 |
|  1 | Google   | https://www.google.cm/    |   230 |
|  2 | 淘宝     | https://www.taobao.com/   |    10 |
|  3 | 菜鸟教程 | http://www.runoob.com/    |   100 |
|  3 | 菜鸟教程 | http://www.runoob.com/    |   220 |
|  3 | 菜鸟教程 | http://www.runoob.com/    |   201 |
|  4 | 微博     | http://weibo.com/         |  NULL |
|  5 | Facebook | https://www.facebook.com/ |   205 |
|  5 | Facebook | https://www.facebook.com/ |   545 |
|  6 | 百度     | http://www.baidu.com      |  NULL |
+----+----------+---------------------------+-------+
10 rows in set (0.00 sec)

where:“id=4”的记录不返回,且没有“count=NULL”的记录

mysql> select w.id, w.name, w.url, a.count from Websites as w right join access_log as a on w.id = a.site_id where w.id != 4 and a.site_id != 4;
+------+----------+---------------------------+-------+
| id   | name     | url                       | count |
+------+----------+---------------------------+-------+
|    1 | Google   | https://www.google.cm/    |    45 |
|    3 | 菜鸟教程 | http://www.runoob.com/    |   100 |
|    1 | Google   | https://www.google.cm/    |   230 |
|    2 | 淘宝     | https://www.taobao.com/   |    10 |
|    5 | Facebook | https://www.facebook.com/ |   205 |
|    3 | 菜鸟教程 | http://www.runoob.com/    |   220 |
|    5 | Facebook | https://www.facebook.com/ |   545 |
|    3 | 菜鸟教程 | http://www.runoob.com/    |   201 |
+------+----------+---------------------------+-------+
8 rows in set (0.00 sec)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值