如何使用单个查询计算2个不同表中2个字段之间的差异?

时间:2011-08-05 23:58:26

标签: sql select

Table Users : user_id , credits_available
Table Survey : user_id, survey_id, credits_required

现在我想计算特定user_id和指定survey_id的credits_available和credits_required之间的差异?是否可以编写单个查询而不是通过2个不同的查询单独计算?

3 个答案:

答案 0 :(得分:3)

select credits_required - credits_available
from Table1 t1 join Table2 t2 on t1.user_id = t2.user_id
where survey_id = survey_id_parameter

答案 1 :(得分:1)

MySQL允许您使用普通数学...

SELECT (survey.credits_required - users.credits_available) as endResult
FROM users,survey 
WHERE users.user_id = survey.user_id 
AND survey_id = $surveyID
AND users.user_id = $userID

当然,$surveyID是一个列出相关调查ID的变量... $userID是一个列出相关用户ID的变量...

答案 2 :(得分:1)

select a.user_id,b.survey_id, (b.credits_required - a.credits_available) as credit_difference from Users a, Survey b where a.user_id = b.user_id and b.Survey_ID = {id parameter}

更好地创建存储过程

create procedure getDifference
@SurveyID int,
@UserID int
AS
SELECT a.user_id, b.survey_id,
       (b.credits_required - a.credits_available) as credit_difference
FROM Users a, Survey b
WHERE a.user_id = b.user_id and b.Survey_ID = @SurveyID and a.User_id = @UserID

执行它

exec getDifference {put your survey id here}, {user id here}