2012-06-01 75 views
0

我有用來獲取一些事件主查詢,這些子查詢:Mysql的子查詢優化 - 計數

WEventUser的
SELECT [...], 
(SELECT COUNT(*) FROM WEventUser WHERE WEventUser.eID=e.eID AND favorited=1) as numfavorited, 
(SELECT COUNT(*) FROM WEventUser WHERE WEventUser.eID=e.eID AND subscribed=1) as numsubscribed, 
(SELECT COUNT(*) FROM WEventUser WHERE eID=e.eID AND WEventUser.uID=2 AND favorited=1) as favorited, 
(SELECT COUNT(*) FROM WEventUser WHERE eID=e.eID AND WEventUser.uID=2 AND subscribed=1) as subscribed, 
[...] WHERE...etc. 

結構相當簡單

CREATE TABLE IF NOT EXISTS `WEventUser` (
    `eID` int(10) unsigned NOT NULL auto_increment, 
    `uID` int(10) unsigned NOT NULL, 
    `favorited` int(1) unsigned default '0', 
    `subscribed` int(1) unsigned default '0', 
    PRIMARY KEY (`eID`,`uID`) 
) ENGINE=MyISAM DEFAULT CHARSET=utf8; 

這些子查詢是真的很貴。你能幫我找到一個替代方案嗎?

在此先感謝!

編輯: 我從主WEvents表即選擇:

CREATE TABLE IF NOT EXISTS `wevents` (
`eID` int(10) unsigned NOT NULL AUTO_INCREMENT, 
`uID` int(10) unsigned DEFAULT NULL, 
`ecID` int(10) unsigned NOT NULL, 
`eName` varchar(64) NOT NULL, 
`eDescription` longtext, 
`eIsActive` varchar(1) NOT NULL DEFAULT '0', 
`eIsValidated` tinyint(4) NOT NULL DEFAULT '-1', 
`eDateAdded` datetime NOT NULL DEFAULT '0000-00-00 00:00:00', 
`eDateModified` datetime NOT NULL DEFAULT '0000-00-00 00:00:00', 
PRIMARY KEY (`eID`,`ecID`) 
) ENGINE=InnoDB DEFAULT CHARSET=utf8; 
+0

查詢中的e.eID是什麼。請分享第二個表格結構 –

回答

2

你不應該使用一個子查詢,這是不夠的COUNT函數計算的值,例如 -

SELECT [...], 
COUNT(IF(wu.favorited = 1, 1, NULL)) as numfavorited, 
COUNT(IF(wu.subscribed = 1, 1, NULL)) as numsubscribed, 
COUNT(IF(wu.uID=2 AND wu.favorited=1, 1, NULL)) as favorited, 
COUNT(IF(wu.uID=2 AND wu.favorited = 1, 1, NULL)) as subscribed, 
[...] 
FROM 
    WEventUser wu 
WHERE...etc. 

,如果你想加入WEventUser與另一個表可以很容易地使用這一個。

+0

我正在從其他表格中選擇數據,但我以這種方式使用您的解決方案: 'SELECT [...], COUNT(IF(wu.favorited = 1,1, NULL))as numfavorited, COUNT(IF(wu.subscribed = 1,1,NULL))as numsubscribed, COUNT(IF(wu.uID = 2 AND wu.favorited = 1,1,NULL))as favorited, COUNT(IF(wu.uID = 2 AND wu.favorited = 1,1,NULL)), [...] FROM WEvents we left weventventUser wu ON wu.euID = e.eID' 它的工作原理!謝謝! –