Answer the question
In order to leave comments, you need to log in
How to display all fields with the maximum match of field values?
There is a table
id user_id data
1 - 1 - Hare
2 - 1 - Wolf
3 - 1 - Bear
4 - 2 - Hare
5 - 2 - Fox
6 - 3 - Hare
7 - 4 - Bear
8 - 4 - Wolf
9 - 4 - Hare
10 - 4 - Orangutan
11 - 5 - Troll
12 - 5 - Fox
Need to print in this order (the order is the same as mine) -
for the user - display the data of the user (s)
1 - 4 (because they all match ), then 2 and 3 (since one field matches)
2 - 1, 3, 4, 5 (one field matches)
3 - display all except the 5th user
4 - 1, 2, 3
5 - 2
I hope I explained it correctly, if I explain it in words - you need to find the intersection of data with other users for the user and sort it in descending order depending on how much data matched
Answer the question
In order to leave comments, you need to log in
SELECT `t`.`user_id` AS `user1`, `s`.`user_id` AS `user2`, count(`s`.`user_id`) AS `num`
FROM `table` AS `t`
JOIN `table` AS `s` ON (`t`.`data` = `s`.`data` AND `t`.`user_id` != `s`.`user_id`)
GROUP BY `user1`, `user2`
ORDER BY `user1`, `num` DESC, `user2`
select u1.*, u2.*
from users u1, users u2
where u1.data = u2.data and u1.id <> u2.id
order by u1.id
I redesigned the query so that it also displays usernames, as well as matched data, and how to display in the same query all the data (data) that did not match as NOEQ
SELECT CONCAT(`t`.`user_id`, ' | ', `u1`.`name`) AS `user1`, CONCAT(`s`.`user_id`, ' | ', `u2`.`name`) AS `user2`, count(`s`.`user_id`) AS `num`,
GROUP_CONCAT(`t`.`data`) as EQ
FROM `user_data` AS `t`
JOIN `user_data` AS `s` ON (`t`.`data` = `s`.`data` AND `t`.`user_id` != `s`.`user_id`)
JOIN `users` AS `u1` ON(`u1`.`id` = `t`.`user_id`)
JOIN `users` AS `u2` ON(`u2`.`id` = `s`.`user_id`)
where `t`.`user_id` = 7
GROUP BY `user1`, `user2`
ORDER BY `user1`, `num` DESC, `user2`
SELECT CONCAT(`t`.`user_id`, ' | ', `u1`.`name`) AS `user1`, CONCAT(`s`.`user_id`, ' | ', `u2`.`name`) AS `user2`, count(`s`.`user_id`) AS `num`,
GROUP_CONCAT(`s`.`data`) as NEEQ
FROM `user_data` AS `t`
JOIN `user_data` AS `s` ON (`t`.`data` != `s`.`data` AND `t`.`user_id` != `s`.`user_id`)
JOIN `users` AS `u1` ON(`u1`.`id` = `t`.`user_id`)
JOIN `users` AS `u2` ON(`u2`.`id` = `s`.`user_id`)
where `t`.`user_id` = 7
GROUP BY `user1`, `user2`
ORDER BY `user1`, `num` DESC, `user2`
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question