2013-04-03 69 views
0

這裏是我的查詢:MySQL的計數顯示更多的結果比預期

SELECT COUNT(*) FROM jos_mls AS mls 
    INNER JOIN jos_activeagents AS active ON active.AGENTUID = mls.MSTLISTBRD 
    AND mls.MSTACTSTA = 'Active' OR mls.MSTACTSTA = 'Keep Showing'; 

的表是相當大的,所以這將是難以顯示錶結構。

當我運行沒有AND mls.MSTACTSTA = 'Active' OR mls.MSTACTSTA = 'Keep Showing'的計數,我得到一個預期的結果(約500)。但是當我想用這些參數過濾掉時,它會返回25000+個結果,當它應該在500以下時。

我想這是一個語法問題,但查找類似的問題,我無法想出一個解決方案。

回答

0

使用WHERE條款

SELECT COUNT(*) FROM jos_mls AS mls 
    INNER JOIN jos_activeagents AS active ON active.AGENTUID = mls.MSTLISTBRD 
    WHERE mls.MSTACTSTA = 'Active' OR mls.MSTACTSTA = 'Keep Showing'; 
+0

不要混用兩個連接語法版本:要麼使用'SELECT * FROM一,b where或'select * from join b on'。 – jurgenreza

0
SELECT COUNT(*) 
    FROM jos_mls mls 
    JOIN jos_activeagents active 
    ON active.AGENTUID = mls.MSTLISTBRD 
    AND (mls.MSTACTSTA = 'Active' OR mls.MSTACTSTA = 'Keep Showing'); 

SELECT COUNT(*) 
    FROM jos_mls mls 
    JOIN jos_activeagents active 
    ON active.AGENTUID = mls.MSTLISTBRD 
    AND mls.MSTACTSTA IN('Active','Keep Showing'); 
0

AND的優先級高於OR所以你應該使用周圍的狀況的第二部分括號來獲得所需的輸出:

SELECT COUNT(*) FROM jos_mls AS mls 
    INNER JOIN jos_activeagents AS active ON active.AGENTUID = mls.MSTLISTBRD 
    AND (mls.MSTACTSTA = 'Active' OR mls.MSTACTSTA = 'Keep Showing'); 

你得到比預計多了很多行的原因是運行實際的查詢是相同的,因爲這一個:建議

SELECT COUNT(*) FROM jos_mls AS mls 
    INNER JOIN jos_activeagents AS active ON (active.AGENTUID = mls.MSTLISTBRD 
    AND mls.MSTACTSTA = 'Active') OR mls.MSTACTSTA = 'Keep Showing';