主表如何统计在附表中的出现次数?

WBOY
发布: 2016-06-01 13:07:05
原创
960 人浏览过

主表如何统计在附表中的出现次数?

建立主表:

create table a1 (id int ,name char(20));
登录后复制

建立附表:

create table a2 (tid int ,name char(20));
登录后复制

分别插入数据:

mysql> insert into a1 values (1,'baidu');Query OK, 1 row affected (0.00 sec)mysql> insert into a1 values (2,'qq');Query OK, 1 row affected (0.00 sec)mysql> insert into a1 values (3,'sina');Query OK, 1 row affected (0.02 sec)mysql> insert into a2 values (1,'000');Query OK, 1 row affected (0.00 sec)mysql> insert into a2 values (1,'001');Query OK, 1 row affected (0.00 sec)mysql> insert into a2 values (1,'002');Query OK, 1 row affected (0.00 sec)mysql> insert into a2 values (1,'003');Query OK, 1 row affected (0.00 sec)mysql> insert into a2 values (2,'200');Query OK, 1 row affected (0.00 sec)mysql> insert into a2 values (2,'201');Query OK, 1 row affected (0.00 sec)mysql> insert into a2 values (2,'202');Query OK, 1 row affected (0.00 sec)mysql> insert into a2 values (2,'203');Query OK, 1 row affected (0.00 sec)mysql> insert into a2 values (2,'204');Query OK, 1 row affected (0.00 sec)mysql> insert into a2 values (2,'205');Query OK, 1 row affected (0.01 sec)mysql> insert into a2 values (3,'300');Query OK, 1 row affected (0.01 sec)
登录后复制

sql语句:

select a.*,(select count(1) from a2 as b where b.tid=a.id) from a1 as a;
登录后复制

这样就能查询a1中所有的id,对应的在a2表中出现了多少次!!

posted on2014-07-12 22:42一生学习,何来毕业阅读(...) 评论(...)编辑

博客园首页博问新闻闪存程序员招聘知识库

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!