mysql:在同一个表上查询三次

时间:2017-08-11 08:46:38

标签: mysql

我目前正在撰写查询。 从帖子(post_views_info)中的用户,帖子和其他信息表中检索信息。

SELECT 
    u.email,
    u.user_nm,
    p.pid,
    p.post_ttl, 
    p.date,
    p.ref_level,
    p.ref_origin,
    p.ref_step,
    date(p.date) = date(now()) AS is_today,
    (SELECT category_path FROM post_category WHERE category_id = p.category_id) as category_full_path,
    (SELECT COUNT(*) FROM post_status_info AS sub_i WHERE sub_i.pid = p.pid AND sub_i.status = 'A') AS recommendCount,
    (SELECT COUNT(*) FROM post_status_info AS sub_i WHERE sub_i.pid = p.pid AND sub_i.status = 'B') AS oppositeCount,
    (SELECT COUNT(*) FROM post_status_info AS sub_i WHERE sub_i.pid = p.pid AND sub_i.status = 'C') AS reportCount
FROM 
    (
        SELECT *
        FROM post as p
        WHERE 
            p.is_enable = 1
        ORDER BY 
            p.ref_origin DESC,
            p.ref_step ASC
    ) as p,
    user AS u
WHERE 
    p.uid = u.uid
ORDER BY 
    ref_origin DESC,
    ref_step ASC

在上面的查询中,我们三次查询同一个表格,以获得帖子的数量' A',' B' C'。'。

为了解决这个问题,我按如下方式更改了查询。

SELECT 
    u.email,
    u.user_nm,
    p.pid,
    p.post_ttl, 
    p.date,
    p.ref_level,
    p.ref_origin,
    psi.reportCount,
    psi.recommendCount,
    psi.oppositeCount,
    p.ref_step,
    date(p.date) = date(now()) AS is_today,
    (SELECT category_path FROM post_category WHERE category_id =     p.category_id) as category_full_path
FROM 
    user AS u,
    (
        SELECT *
        FROM post as p
        WHERE 
            p.is_enable = 1
        ORDER BY 
            p.ref_origin DESC,
            p.ref_step ASC
        LIMIT 0, 15
    ) as p left join
    (
        SELECT 
                pid, 
                COUNT(if(status = 'A', 1, null)) AS reportCount,
                COUNT(if(status = 'B', 1, null)) AS recommendCount,
                COUNT(if(status = 'C', 1, null)) AS oppositeCount
        FROM post_status_info 
        group by pid
    ) AS psi
on 
    psi.pid = p.pid
WHERE 
    p.uid = u.uid
ORDER BY 
    ref_origin DESC,
    ref_step ASC

我认为最好三次查询同一个表。 哪个代码在性能方面更好?

感谢。

1 个答案:

答案 0 :(得分:1)

我认为第二种选择在表现方面更有成效。因为这里我们执行的查询数量较少。

您也可以使用CASE来完成。

SELECT 
u.email,
u.user_nm,
p.pid,
p.post_ttl, 
p.date,
p.ref_level,
p.ref_origin,
p.ref_step,
date(p.date) = date(now()) AS is_today,
(SELECT category_path FROM post_category WHERE category_id = p.category_id) as category_full_path,
(SUM(CASE WHEN sub_i.status = 'A' THEN 1 ELSE 0 END)) AS recommendCount,
(SUM(CASE WHEN sub_i.status = 'B' THEN 1 ELSE 0 END)) AS oppositeCount,
(SUM(CASE WHEN sub_i.status = 'C' THEN 1 ELSE 0 END)) AS reportCount
FROM 
(
    SELECT *
    FROM post as p
    WHERE 
        p.is_enable = 1
    ORDER BY 
        p.ref_origin DESC,
        p.ref_step ASC
) as p,
INNER JOIN user AS u ON u.uid = p.uid
INNER JOIN post_status_info as sub_i ON p.pid = sub_i.pid
GROUP BY p.pid
ORDER BY 
ref_origin DESC,
ref_step ASC