如何按左连接的链接视图排序类别?

bwntbbo3  于 2021-06-25  发布在  Mysql
关注(0)|答案(1)|浏览(388)

我想有一个类别,是从另一个表的总链接视图排序列表。
我只是试着在谷歌上搜索一下,然后想出了这个例子。

SELECT 
    'categories'.'catId',
    'categories'.'title',
    'categories'.'description',
    (
        SELECT SUM(hits)
        FROM 'links'
        WHERE 'catId' = 'categories'.'catId'
    ) AS 'hits_count'
FROM 'categories'
LEFT JOIN 'links'
ON 'links'.'catId' = 'categories'.'catId'
WHERE 'status'='1'
ORDER BY 'hits_count'

这样行吗?还是有别的办法?
最新的尝试

<?php
include 'config.php';
$db = new DB();
$sql="SELECT categories.name,
    (
        SELECT SUM(hits)
        FROM links
        WHERE catId = categories.catId
    ) AS hits_count
FROM categories
LEFT JOIN links
ON links.catId = categories.catId
WHERE links.status=1
ORDER BY hits_count DESC";

$query = $db->db->prepare($sql);
$categories = $query->execute();
?>
<?php print_r($categories) ?>

只带着数字1回来了

mqxuamgl

mqxuamgl1#

我想把它说成是 categories 以及查找和的子查询:

SELECT
    c.catId,
    c.title,
    c.description,
    COALESCE(l.hits_count, 0) AS hits_count
FROM categories c
LEFT JOIN
(
    SELECT catId, SUM(hits) hits_count
    FROM links
    GROUP BY catId
) l
    ON l.catId = c.catId
WHERE
    c.status = 1
ORDER BY
    hits_count;

通过使用连接而不是相关子查询,应该可以提高性能。但也许你面临的更大的问题是,你在每件事上都加了单引号。不要这样做,因为mysql可能会将其解释为字符串文本。如果需要在mysql中转义表或列名,请使用backticks。但就你而言,我认为你根本不需要它们。

相关问题