想要从3个表中获取数据,同时总结1列

时间:2018-06-12 10:09:12

标签: mysql

table (user)
+----------------------+
|id | name | course_id |
|----------------------|
|01 | cena | 24        |
|02 | john | 42        |
+----------------------+

table (courses)
+---------------------------------+
|id | user_id | coursename | fee  |
|---------------------------------|
|24 | 01      | Illustrator| 4000 |
|42 | 02      | Photoshop  | 3000 |
+---------------------------------+

table (fee)
+---------------------------+
|id | user_id | paid_amount |
|---------------------------|
|01 | 01      | 400         |
|02 | 02      | 800         |
|03 | 01      | 600         |
|04 | 02      | 1200        |
+---------------------------+

enter image description here

香港专业教育学院尝试过此查询,但没有工作

$ query =" SELECT A.id,A.name,C.coursename,C.fee,B。'总付费费用'来自'用户' A

LEFT JOIN(SELECT user_id,SUM(paid_amount)'总付费' FROM费用GROUP BY user_id)B ON A.id = B.user_id

LEFT JOIN课程C ON A.id = C.user_id;";

<?php 
    $query = "above query";
    $query = $connect->prepare($query);
    $query->execute();
    if($query->rowCount()):
    while($row = $query->fetch(PDO::FETCH_ASSOC)){
    echo $row['id']; 
    echo $row['name']; 
    echo $row['coursename']; 
    echo $row['fee']; 
    echo $row['total paid fee']; 
    } 
    endif; 
?>

1 个答案:

答案 0 :(得分:0)

删除表格名称中的单引号,例如'user',而您可以使用bacticks , Moreover do not use spaces in aliase name like&#39;总付费费用&#39; instead you can write it as totalPaidFee or total_paid_fee` < / p>

SELECT A.id, 
       A.name, 
       C.coursename, 
       C.fee, 
       B.total_paid_fee, 
       C.fee - B.total_paid_fee AS remaining_fee 
FROM   `user` A 
       LEFT JOIN (SELECT user_id, 
                         Sum(paid_amount) total_paid_fee 
                  FROM   fee 
                  GROUP  BY user_id) B 
              ON A.id = B.user_id 
       LEFT JOIN courses C 
              ON A.id = C.user_id 

Demo