我需要从 PostgreSQL 表中查询预定义的技能等级集。考虑以下包含用户 1、2 和 3 的演示表,每个用户都有不同的技能和技能等级:
╔════════╦═══════════╦═══════╗
║ userId ║ skillId ║ votes ║
╠════════╬═══════════╬═══════╣
║ 1 ║ marketing ║ 50 ║
║ 2 ║ hacking ║ 51 ║
║ 1 ║ business ║ 59 ║
║ 2 ║ business ║ 8 ║
║ 1 ║ hacking ║ 32 ║
║ 3 ║ talking ║ 67 ║
║ 3 ║ business ║ 34 ║
║ 3 ║ marketing ║ 24 ║
╚════════╩═══════════╩═══════╝
现在我想根据加权业务+黑客对它们进行排名:
SELECT * FROM
(SELECT
b."userId",
MAX(CASE WHEN b."skillId"='business' THEN b.votes ELSE 0 END) AS "businessVotes",
MAX(CASE WHEN h."skillId"='hacking' THEN h.votes ELSE 0 END) AS "hackingVotes"
FROM "Skill" b, "Skill" h
WHERE b."userId"=h."userId"
AND (
(b."skillId"='business' AND h."skillId"='hacking') OR
(b."skillId"=h."skillId" AND (b."skillId"='business' OR b."skillId"='hacking'))
)
GROUP BY b."userId") AS query
ORDER BY "businessVotes"*0.2+"hackingVotes"*0.8 DESC
正如预期的那样,我得到以下结果:
╔════════╦═══════════════╦══════════════╗
║ userId ║ businessVotes ║ hackingVotes ║
╠════════╬═══════════════╬══════════════╣
║ 2 ║ 8 ║ 51 ║
║ 1 ║ 59 ║ 32 ║
║ 3 ║ 34 ║ 0 ║
╚════════╩═══════════════╩══════════════╝
但在我看来,这个查询需要 PostgreSQL 做比必要更多的计算,因为复杂地处理用户没有黑客但有商业技能的情况或反之亦然。如果没有这种情况(即需要商业和黑客技能才能进入排名),查询可能会容易得多:
SELECT *
FROM "Skill" t1, "Skill" t2
WHERE t1."userId"=t2."userId"
AND (t1."skillId"='business'
AND t2."skillId"='hacking')
ORDER BY t1."votes"*0.2 + t2."votes"*0.8 DESC;
是因为我的推理错误,不利的表结构还是仅仅因为它就是这样并且没有更好的选择?