mysql 左连接,右连接,内链接,exists等

背景
  1. mysql> select * from grade;
  2. +----+-------+
  3. | no | grade |
  4. +----+-------+
  5. | 1 | 90 |
  6. | 2 | 80 |
  7. | 3 | 70 |
  8. +----+-------+
  9. 3 rows in set (0.00 sec)

mysql> select * from student;
  1. +----+------+
  2. | no | name |
  3. +----+------+
  4. | 1 | a |
  5. | 2 | b |
  6. | 3 | c |
  7. | 4 | d |
  8. +----+------+

内链接(查询两边都有的数据) 等价于   where语句  等价于  join语句
mysql> select * from student s inner join grade g on s.no=g.no;
+----+------+----+-------+
| no | name | no | grade |
+----+------+----+-------+
|  1 | a    |  1 |    90 |
|  2 | b    |  2 |    80 |
|  3 | c    |  3 |    70 |
+----+------+----+-------+
3 rows in set (0.16 sec)


左连接 (左表中所有数据,右表中对应数据)
mysql>  select * from student as s left join grade as 
    -> g on s.no=g.no; 
+----+------+------+-------+
| no | name | no   | grade |
+----+------+------+-------+
|  1 | a    |    1 |    90 |
|  2 | b    |    2 |    80 |
|  3 | c    |    3 |    70 |
|  4 | d    | NULL |  NULL |
+----+------+------+-------+
4 rows in set (0.00 sec)
  1. 左链接优化:
  2. 优化前:
  3. mysql> SELECT COUNT(c_user.uid) AS tp_count FROM `c_user` LEFT JOIN c_devices on c_user.last_did=c_devices.did LIMIT 1;
    +----------+
    | tp_count |
    +----------+
    |  4091879 |
    +----------+
    1 row in set (16.10 sec)
  1. 优化后:
  2. mysql> SELECT COUNT(c_user.uid) AS tp_count FROM `c_user`;
    +----------+
    | tp_count |
    +----------+
    |  4091879 |
    +----------+
    1 row in set (1.28 sec)





右连接(右表中所有数据,左表中对应数据)  
mysql> select * from student as s right join grade as g on s.no=g.no; 
+------+------+----+-------+
| no   | name | no | grade |
+------+------+----+-------+
|    1 | a    |  1 |    90 |
|    2 | b    |  2 |    80 |
|    3 | c    |  3 |    70 |
+------+------+----+-------+
3 rows in set (0.00 sec)



Mysql数据库中的EXISTS和NOT EXISTS

金山面试题


题目如下:
数据库1中存放着a类数据,数据库2中存放着以天为单位划分的表30张(比如table_20110909,table_20110910,table_20110911),总共是一个月的数据。表1中的a类数据中有一个字段userid来唯一判别用户身份,表2中的30张表(每张表结构相同)也有一个字段userid来唯一识别用户身份。如何判定a类数据库的多少用户在数据库2中出现过?

1)各位高手能否说一下这道题的考点是什么
2)能否说一下你们的实现思路或者关键的sql语句
select count(*) from 数据库1.a类数据 
where exists (select 1 from 数据库2.table_20110909 where userid = 数据库1.a类数据.userid)
or exists (select 1 from 数据库2.table_20110910 where userid = 数据库1.a类数据.userid)
or exists (select 1 from 数据库2.table_20110911 where userid = 数据库1.a类数据.userid)



来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/29096438/viewspace-1873884/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/29096438/viewspace-1873884/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值