因為公司產品的需求,現在要去實現一個功能,表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語句也沒有錯誤但是結果就是不對。