SQL结果返回总行而不是指定

时间:2013-12-14 06:30:57

标签: mysql sql

基本上,我有这个查询

SELECT p.*, total, active_total
FROM proxies p
LEFT JOIN   
        (SELECT proxy_id, COUNT(*) as total 
        FROM creator_log 
        GROUP BY proxy_id) p2
        ON p.proxy_id = p2.proxy_id
JOIN 
        (SELECT proxy_id, COUNT(*) as active_total 
        FROM accounts
        WHERE status = 1) p3
        ON p.proxy_id = p3.proxy_id
WHERE 
    p.proxy_status = '1'
ORDER BY 
    p2.proxy_id DESC
LIMIT 1

active_total的值是返回accounts表中的总行数,它应该找到从proxy_id结果返回LEFT JOIN的帐户,

为什么它表现奇怪?

1 个答案:

答案 0 :(得分:1)

假设您的帐户表包含以下条目

proxy_id    |  field1   
   1           some_value     
   2           some_value     
   3           some_value     
   4           some_value     

并查询

SELECT proxy_id, COUNT(*) as active_total 
FROM accounts
WHERE status = 1

结果

proxy_id    |  active_total 
   1            4

因此,当离开加入时,您的预期结果将无法获得。它只会产生总记录

试试这个

SELECT p.*, total, active_total
FROM proxies p
LEFT JOIN   
        (SELECT proxy_id, COUNT(*) as total 
        FROM creator_log 
        GROUP BY proxy_id) p2
        ON p.proxy_id = p2.proxy_id
JOIN 
        (SELECT proxy_id, COUNT(proxy_id) as active_total 
        FROM accounts
        WHERE status = 1
        GROUP BY proxy_id ) p3
        ON p.proxy_id = p3.proxy_id
WHERE 
    p.proxy_status = '1'
ORDER BY 
    p2.proxy_id DESC
LIMIT 1