对于每个图像,选择三个标签中的哪一个是最好的。然后选择其中最好的。
您可以使用 MySQL 中的以下技巧为每个图像选择最佳的:
select i.id, max(score) as maxscore,
substring_index(group_concat(it.tag_id order by score desc, rand()), ',', 1) as prefTag
from image i join
acme_images_tags it
on i.id = it.image_id and
it.tag_id in (20, 21, 22)
group by i.id;
复杂的表达式prefTag
为每个图像选择得分最高的标签。rand()
可以处理平局,以确保所有具有相同最佳分数的标签都有相同的机会。
然后,您可以使用相同的想法为每个标签选择最佳图像:
select prefTag,
substring_index(group_concat(id order by maxscore desc), ',', 1) as image_id
from (select i.id, max(score) as maxscore,
substring_index(group_concat(it.tag_id order by score desc, rand()), ',', 1) as prefTag
from image i join
acme_images_tags it
on i.id = it.image_id and
it.tag_id in (20, 21, 22)
group by i.id
) t
group by prefTag
这比我之前使用的解决方案更简单(但等效)union all
。我把它留在下面。
(select i.id, max(score) as maxscore,
substring_index(group_concat(it.tag_id order by score desc), ',', 1) as prefTag
from image i join
acme_images_tags it
on i.id = it.image_id and
it.tag_id in (20, 21, 22)
group by i.id
having preftag = 20
order by maxscore desc
limit 1
) union all
(select i.id, max(score) as maxscore,
substring_index(group_concat(it.tag_id order by score desc), ',', 1) as prefTag
from image i join
acme_images_tags it
on i.id = it.image_id and
it.tag_id in (20, 21, 22)
group by i.id
having preftag = 21
order by maxscore desc
limit 1
) union all
(select i.id, max(score) as maxscore,
substring_index(group_concat(it.tag_id order by score desc), ',', 1) as prefTag
from image i join
acme_images_tags it
on i.id = it.image_id and
it.tag_id in (20, 21, 22)
group by i.id
having preftag = 22
order by maxscore desc
limit 1
)