【发布时间】:2010-09-27 17:58:27
【问题描述】:
这更像是一种偏好,但我想知道人们认为什么是执行的最佳选择。我有一个问题、答案和观点(因为我需要跟踪哪个用户提出了观点)
表转储
Question:
id
title
Answer:
id
question_id
user_id
response
Point_Answer:
id
answer_id
user_id
points
因此,在此布局中要获得最佳答案将需要复杂的连接序列。
SELECT t2.id, t2.user_id, t2.response, MAX(points)
FROM Question as t1,
(SELECT qa.*, SUM(pa.points) as points
FROM answer as qa, Point_Answer as pa
WHERE qa.id = pa.answer_id
GROUP BY qa.id) as t2
WHERE t1.id = %s AND t1.id = t2.question_id
如果我这样改的话:
Question:
id
title
Answer:
id
question_id
user_id
response
points
Point_Answer:
id
answer_id
user_id
points
查询会减轻负担
SELECT A.id, A.user_id, A.response, MAX(points)
FROM Question as Q, Answer as A
WHERE Q.id = %s AND Q.id = A.question_id
GROUP BY A.id
还意味着我必须确保添加 Point_Answer 时添加 Answer.points。所以基本上是一个额外的更新。基本上是“完整性与冗余”和一些优化,更好的方法是什么?
【问题讨论】:
标签: sql database-design query-optimization