Mysql joins multiple tables when query results are out of the question

Source: Internet
Author: User

Because of the company's product needs, now to implement a function, table A put the user's basic information, table B saved a table of the user's behavior, table C and table B the same nature. When asked to query the time can be in B or C table in the count results to sort, so think of join, but there is a problem.

The data structure of 3 sheets is posted first

  CREATE TABLE `A` (  `id` int(11) NOT NULL auto_increment,  `username` varchar(255) default NULL,  PRIMARY KEY  (`id`),) ENGINE=MyISAM AUTO_INCREMENT=1;
  CREATE TABLE `B` (  `id` int(11) NOT NULL auto_increment,  `userid` int(11) default NULL,  `dosomething` varchar(255) default NULL,  PRIMARY KEY  (`id`),  KEY `userid` USING BTREE (`userid`)) ENGINE=MyISAM AUTO_INCREMENT=1;
  CREATE TABLE `C` (  `id` int(11) NOT NULL auto_increment,  `userid` int(11) default NULL,  `dosomething` varchar(255) default NULL,  PRIMARY KEY  (`id`),  KEY `userid` USING BTREE (`userid`)) ENGINE=MyISAM AUTO_INCREMENT=1;

Make your own attempt to find that the query results are different

SELECT u.id, COUNT(s.id) AS sapply, COUNT(uu.id) AS ftotal FROM A AS u RIGHT JOIN B AS s ON u.id = s.userid RIGHT JOIN C AS uu ON u.id = `uu`.`userid` GROUP BY `u`.`id` ORDER BY `ftotal` DESC LIMIT 10

The data is obviously problematic, and the results are separated.

SELECT u.id, COUNT(s.id) AS sapply FROM A AS u RIGHT JOIN B AS s ON u.id = s.userid GROUP BY `u`.`id` ORDER BY `sapply` DESC LIMIT 10

SELECT u.id, COUNT(uu.id) AS ftotal FROM A AS u RIGHT JOIN C AS uu ON u.id = uu.userid GROUP BY `u`.`id` ORDER BY `ftotal ` DESC LIMIT 10

Let's see what the problem is. The first SQL statement is no error, but the result is not.

  • 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.