i\'m making an e-store, so i have 3 tables:
1) goods
id | title
--------+-----------
1 | Toy car
2 | Toy pony
3 | Do
This query will return all items that have the maximum number of tags in common:
SET @item = 1;
SELECT
goods_id
FROM
links
WHERE
tag_id IN (SELECT tag_id FROM links WHERE goods_id=@item)
AND goods_id!=@item
GROUP BY
goods_id
HAVING
COUNT(*) = (
SELECT
COUNT(*)
FROM
links
WHERE
tag_id IN (SELECT tag_id FROM links WHERE goods_id=@item)
AND goods_id!=@item
GROUP BY
goods_id
ORDER BY
COUNT(*) DESC
LIMIT 1
)
Please see fiddle here.
Or this one will return all items, even those with no tags in common, ordered by the number of tags in common desc:
SELECT
goods_id
FROM
links
WHERE
goods_id!=@item
GROUP BY
goods_id
ORDER BY
COUNT(CASE WHEN tag_id IN (SELECT tag_id FROM links WHERE goods_id=@item) THEN 1 END) DESC;