我从数据库中获取标签,并且想要对结果顶部的表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
答案 0 :(得分:0)
解决方案:
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