Php 订购顶部带有匹配项的标签

Php 订购顶部带有匹配项的标签,php,mysql,sql,Php,Mysql,Sql,我从数据库中获取标记,并对结果顶部表tag\u posts中匹配的标记进行排序。它几乎可以工作了,但是我得到了重复的,因为组byc\u p\u id。但是如果我按顺序从组中删除c\u p\u id,有时会获取错误的行。使用一些IF-EXIST选项是否更有意义 我希望标签如下所示: TAG B TAG A TAG C 如果TAG-B在TAG\u posts中有点击 SELECT c_p_id, t_id, t_title FROM tags LEFT JOIN projects ON p_id

我从数据库中获取标记,并对结果顶部表
tag\u posts
中匹配的标记进行排序。它几乎可以工作了,但是我得到了重复的,因为组by
c\u p\u id
。但是如果我按顺序从组中删除
c\u p\u id
,有时会获取错误的行。使用一些IF-EXIST选项是否更有意义

我希望标签如下所示:

TAG B
TAG A
TAG C
如果TAG-B在
TAG\u 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
解决方案:

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
看见