【问题标题】:Order tags with matches at the top顶部有匹配项的订单标签
【发布时间】:2018-07-27 04:51:09
【问题描述】:

我从数据库中获取标签,我想对结果顶部的表tag_posts 中匹配的标签进行排序。它接近工作,但由于c_p_id 的组,我得到了重复。但是,如果我按顺序从组中删除c_p_id,有时会获取错误的行。使用一些 IF EXIST 选项是否更有意义?

我希望标签像这样列出:

TAG B
TAG A
TAG C

如果 TAG-B 在tag_posts 中有命中。

SELECT c_p_id, t_id, t_title
FROM tags
LEFT JOIN projects
ON p_id = " . $p_id . "
LEFT JOIN tag_posts
ON tp_t_id = t_id
LEFT JOIN cats
ON c_id = tp_c_id
AND c_p_id = p_id
GROUP BY t_id, c_p_id
ORDER BY c_p_id DESC, t_title ASC

// 编辑。我想出了一个不同的解决方案来做我想做的事:

SELECT t_id, t_title, 
    (SELECT 1 FROM tag_posts
        INNER JOIN cats
            ON c_id = tp_c_id
        INNER JOIN projects
            ON p_id = c_p_id
        WHERE tp_t_id = t_id
            AND p_id = " . $p_id . "
        LIMIT 1) used
FROM tags
ORDER BY used DESC, t_title ASC

【问题讨论】:

标签: php mysql sql


【解决方案1】:

解决方案:

SELECT t_id, t_title, 
    (SELECT 1 FROM tag_posts
        INNER JOIN cats
            ON c_id = tp_c_id
        INNER JOIN projects
            ON p_id = c_p_id
        WHERE tp_t_id = t_id
            AND p_id = " . $p_id . "
        LIMIT 1) used
FROM tags
ORDER BY used DESC, t_title ASC

【讨论】:

    猜你喜欢
    • 2021-06-25
    • 2012-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-16
    • 2013-03-06
    • 2016-06-11
    • 2011-04-04
    相关资源
    最近更新 更多