如何通过外键匹配对sql结果进行排名

时间:2015-02-12 18:58:00

标签: php mysql

如何根据匹配最多的外键ID对结果进行排名?

例如:

$tag_ids = '1, 2, 3';

$sql = "SELECT * 
FROM `posts` p 
LEFT JOIN `tags_posts` tp 
ON tp.`post_id` = p.`id`
WHERE
tp.`tag_id` IN (". $tag_ids .")";

表:poststagstags_posts(联接表)

一个帖子可以有很多标签

一个标签可以属于许多帖子

如何对具有最匹配标记ID的帖子进行排名($ tag_ids)

编辑:

I need to use this in a larger UNION query

$sql_1 = "SELECT `id`, `date`, ... FROM `first_table` ... LEFT JOIN ... GROUP BY `first_table`.`id`";

$sql_2 = "SELECT `id`, `date`, ... FROM `second_table` ... LEFT JOIN ... GROUP BY `second_table`.`id`";

$sql_3 = "SELECT `id`, `date`, ... FROM `third_table` ... LEFT JOIN ... GROUP BY `third_table`.`id`";

$sql = " SELECT * FROM ( 
" . $sql_1 . "
UNION
" . $sql_2 . "
UNION
" . $sql_3 . "
) as t
ORDER BY t.`date` DESC
";

1 个答案:

答案 0 :(得分:0)

按tag_id分组,然后计算每个组。最大的计数是最匹配的。