How does a primary table count the number of occurrences in the attached table?

Source: Internet
Author: User
How does a primary table count the number of occurrences in the attached table?

How does a primary table count the number of occurrences in the attached table?

Create a master table:

create table a1 (id int ,name char(20));

Create a schedule:

create table a2 (tid int ,name char(20));

Insert data separately:

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 statement:

select a.*,(select count(1) from a2 as b where b.tid=a.id) from a1 as a;

In this way, you can query the number of IDs in table A1 !!

Posted on2014-07-12 life learning, he Lai graduation reading (...) comment (...) Edit

Blog homepage blog news flash programmer recruitment knowledge base

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.