多表,多列查询

时间:2012-07-04 11:12:32

标签: mysql

我有以下表格:

交易Transaction_ID Datetime Giver_ID Recipient_ID Points Category_ID Reason

奖励Reward_ID Title Description Image_URL Date_Inactive Stock_Count Cost_to_User {{1 }}

购买Cost_to_System Purchase_ID Datetime Reward_ID Quantity Student_ID Student_Name {{1 }}


工作人员通过积分奖励学生,这将成为交易表的一个条目,如下所示:

Date_DealtWith Date_Collected Transaction_ID Datetime Giver_ID Recipient_ID Points
Category_ID Reason 8 2011-09-07 36761 127963 2

学生可以购买奖励,这将成为购物表的一个条目,如下所示:

1 Excellent behaviour in behaviour unit Purchase_ID Datetime Reward_ID Quantity Student_ID Student_Name
Date_DealtWith Date_Collected 1570 2012-05-30 12:46:36 2 1 137616 Bradley Richardson

所有奖励都手动存储在奖励数据库表中:

NULL NULL Reward_ID Title Description Image_URL Date_Inactive Stock_Count
Cost_to_User Cost_to_System 1 Lunch Time Queue Pass (month) Beat the queue and get to the hot food early! /user/74/167976.png 2012-04-16 11:50:00 0


我的问题是:

我可以使用哪种SQL语句返回学生姓名,获得的积分,已用积分,剩余积分

我问a similar question a while back,提出以下声明。但是,经过检查,它似乎并不完全准确 - 特别是积分无法正常工作。

100

提前致谢,

2 个答案:

答案 0 :(得分:3)

您只需使用outer join组合表格,然后按学生分组:

SELECT purchases.Student_Name                               AS `Student Name`,
       SUM(transactions.Points)                             AS `Points Earned`,
       SUM(rewards.Cost_to_User)                            AS `Points Spent`,
       SUM(transactions.Points) - SUM(rewards.Cost_to_User) AS `Points Remaining`
FROM   transactions
  LEFT JOIN purchases ON purchases.Student_ID = transactions.Recipient_ID
  LEFT JOIN rewards   USING (Reward_ID)
GROUP BY purchases.Student_ID
ORDER BY `Points Remaining` DESC

答案 1 :(得分:1)

我愚蠢地意识到另一篇文章中的一个小错误修复了我遇到的问题:

SELECT SumOfPointsEarned.Points - COALESCE(SumOfPointsOfPurchasesMade.Points, 0) AS CurrentPoints
FROM   
(
    SELECT SUM(Points) AS Points, Recipient_ID 
    FROM   transactions 
            WHERE Recipient_ID= 137642
    GROUP  BY Recipient_ID
) AS SumOfPointsEarned 
    LEFT JOIN 
    (
        SELECT purchases.Student_ID,  SUM(rewards.Cost_to_User * purchases.Quantity) AS Points 
        FROM   purchases 
            INNER JOIN rewards 
            ON purchases.Reward_ID = rewards.Reward_ID 
                    WHERE Student_ID = 137642
        GROUP  BY purchases.Student_ID
    ) AS SumOfPointsOfPurchasesMade 
    ON SumOfPointsEarned.Recipient_ID = SumOfPointsOfPurchasesMade.Student_ID
ORDER BY CurrentPoints ASC

这一行是问题所在:

SUM(rewards.Cost_to_User * purchases.Quantity) AS Points

没有数量的倍增。卫生署!