Question

Hi I'm very bad at writing mysql queries (I'm working on it).

Could you guys help me with this one?

I have a table of tags:

id | tag
--------------------------------
1  | css
2  | c++
3  | perl
4  | sql
5  | pyhton

Another table of PostsA_tags:

id | postID | tag
--------------------------------
1  | 1      | 1
2  | 1      | 2
3  | 2      | 1
4  | 2      | 3
5  | 3      | 3

Another table of PostsB_tags:

id | postID | tag
--------------------------------
1  | 1      | 2
2  | 2      | 3
3  | 2      | 1
4  | 3      | 4
5  | 3      | 5

Another table of PostA:

postID | info
--------------------------------
1      | this
2      | is
2      | infor
3      | mation
4      | lol

Another table of PostB:

postID | info
--------------------------------
1      | more
2      | infor
3      | mation
4      | please
5      | hahaha

So now, the challenge is to order B posts from the A posts.

This means that if Peter is the owner of A posts, we need to get all his tags from all his posts. In this case it would be:

css, c++, perl

While, Sam is the owner of B posts. Now we need to order Sam's posts (B posts), by the amount of coincidences between Peter's tags (A tags) and the tags from each Sam's post.

In this case it would be:

B Posts ordered by coincided factor DESC

postID | info
--------------------------------
2      | infor 
1      | more
3      | mation
4      | please
5      | hahaha

I'm really stuck. I know how to get Sam's tags. But not how to measure the coincidence factor between Sam's tags and the tags from each Peter's post.

Sorry for my english :S

Thanks in advance

Here's a fiddle... sqlfiddle.com/#!2/8450c/3

Was it helpful?

Solution

I think I have resolved the problem.

Here is the query

SELECT *, SUM(`PostsA_tags`.`tag` = `PostsB_tags`.`tag`) as rel FROM `PostsB_tags`
LEFT OUTER JOIN `PostsA_tags` `PostsA_tags` ON(`PostsA_tags`.`tag` = `PostsB_tags`.`tag`)
GROUP BY `PostsB_tags`.`postID`
ORDER BY rel DESC
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top