虽然这个问题应该被认为太宽泛,不适合在这里(请在提问之前尝试一些东西!),这对我来说很有趣来回答它。
我不会在 PHP 中这样做,而是在纯 SQL 中这样做。
假设这样的结构:
CREATE TABLE game (
game_id INT PRIMARY KEY,
name VARCHAR(50)
);
CREATE TABLE tag (
tag_id INT PRIMARY KEY,
label VARCHAR (50)
);
CREATE TABLE gametag (
game_id INT,
tag_id INT,
rank INT, -- ranks from 1 to 5, rank "1" will weightmeans "5 points"
PRIMARY KEY (game_id, tag_id),
UNIQUE (game_id, tag_id, rank),
CONSTRAINT gid_fk FOREIGN KEY gid_fk_idx (game_id) REFERENCES game (game_id),
CONSTRAINT tid_fk FOREIGN KEY tid_fk_idx (tag_id) REFERENCES tag (tag_id)
);
两个游戏之间的“匹配分数”将通过如下查询获得:
SELECT
game1.name AS game_1,
game2.name AS game_2,
SUM(match_score) AS score
FROM (
SELECT
game1.game_id AS game1_id,
game2.game_id AS game2_id,
(6 - gametag1.rank) * (6 - gametag2.rank) AS match_score -- modify the magic "6" if you allow more or less than 5 tags
FROM game AS game1
JOIN gametag AS gametag1 USING (game_id)
JOIN tag AS tag1 USING (tag_id)
JOIN tag AS tag2 USING (tag_id)
JOIN gametag AS gametag2 USING (tag_id)
JOIN game AS game2 ON game2.game_id = gametag2.game_id
WHERE game1.game_id = 1 AND game2.game_id = 2
) AS scores
JOIN game AS game1 ON game1.game_id = game1_id
JOIN game AS game2 ON game2.game_id = game2_id
GROUP BY game1_id, game2_id;