dotwc62080 2018-07-26 06:31
浏览 78
已采纳

订单标记顶部带有匹配项

I fetch tags from a database and I want to sort the tags that have matches in the table tag_posts at the top of the result. It is close to working, but I get duplicates because of the group by c_p_id. But if I remove c_p_id from the group by the order by sometimes fetches the wrong row. Would it make more sense to use some IF EXIST option?

I want the tags to be listed like this:

TAG B
TAG A
TAG C

If TAG-B has a hit in 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

// EDIT. I figured out a different solution that is doing what I want:

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条回答 默认 最新

  • doupishan3309 2018-07-26 20:51
    关注

    Solution:

    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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序