【发布时间】: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
【问题讨论】: