我从数据库中获取标签,并且想要对结果顶部的表 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
最佳答案
解决方案:
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 - 对顶部匹配的标签进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51532341/