Table Users : user_id , credits_available
Table Survey : user_id, survey_id, credits_required
现在我想计算特定user_id和指定survey_id的credits_available和credits_required之间的差异?是否可以编写单个查询而不是通过2个不同的查询单独计算?
答案 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}