Rumah > Artikel > pembangunan bahagian belakang > Mysql join 多张表时查询结果出了问题
因为公司产品的需求,现在要去实现一个功能,表A放的用户的基本信息,表B存的A表中用户的一些行为,表C和表B的性质一样。要求查询的时候可以按照B表或者C表中的count结果进行排序,于是就想到了join,可是出现了问题。
先贴出3张表的数据结构
<code> CREATE TABLE `A` ( `id` int(11) NOT NULL auto_increment, `username` varchar(255) default NULL, PRIMARY KEY (`id`), ) ENGINE=MyISAM AUTO_INCREMENT=1;</code>
<code> 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;</code>
<code> 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;</code>
自己做出尝试,发现查询结果不一样
<code>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</code>
数据明显有问题,分开关联看结果
<code>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</code>
<code>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</code>
大家帮忙看看,这问题出在哪呢 第一条Sql语句也没有错误但是结果就是不对。