代码之家  ›  专栏  ›  技术社区  ›  SeaBass

订购顶部有匹配项的标签

  •  0
  • SeaBass  · 技术社区  · 7 年前

    我从数据库中提取标记,并对表中具有匹配项的标记进行排序 tag_posts 在结果的顶部。很快就要开始工作了,但我因为分组而收到了副本。 c_p_id . 但是如果我删除 C-PyID 有时按顺序从组中取出错误的行。使用一些“如果存在”选项是否更有意义?

    我希望标签如下所示:

    TAG B
    TAG A
    TAG C
    

    如果TAG-B中有人 塔格柱 .

    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
    
    1 回复  |  直到 7 年前
        1
  •  0
  •   SeaBass    7 年前

    解决方案:

    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
    
    推荐文章