I have two MySQL tables: Articles
and SimilarArticles
.
CREATE TABLE `Articles` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`text` text,
`priority` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
)
CREATE TABLE `SimilarArticles` (
`article_id` int(11) unsigned NOT NULL,
`similar_article_id` unsigned NOT NULL,
PRIMARY KEY (`article_id`,`similar_article_id`)
)
SimilarArticles
is a simple relationship table to track similar article records.
User totymedli in this post has a good explanation how to SELECT similar records in this scenario which works fine.
But now I have to create a SELECT statement which makes sure that there are no similar articles in the result. So for all groups of similar articles in the table only the record with the highest value in field priority
should get into the result set.
So far I haven't figured out an approach for this. Has anyone an idea how to do this efficiently in MySQL?
EXAMPLE:
Table Articles
id text priority
1 FooA 1
2 Bar 1
3 FooB 3
4 FooC 2
5 Baz 9
Table SimilarArticles
article_id similar_article_id
1 3
4 1
3 4
The SELECT statement i'm trying to create should return:
id text priority
2 Bar 1
3 FooB 3
5 Baz 9
Because FooA, FooB und FooC are similar according to the SimilarArticles
table and FooB has the highest priority
of these three records, only FooB should be in the result set (together with Bar and Baz, which have no similar records).