doushoubu5360 2015-12-30 00:55
浏览 63
已采纳

用4个表编写复杂的SQL查询

I have 4 tables from which i want to output information with a single query and i'm not sure how to do that.

• From table1 i want to get all the records

• For each record from table1 i want to take out the SUM from field1 from all records in table2 on a matching id taken from table1

• For each record from table1 i want to take out the SUM from field1 from all records in table3 on a matching id taken from table1

• For each record from table1 i want to take out the value of a single record from table4 on a matching id taken from table1

EDIT:

Here is how i think the graphic for my request should look: enter image description here

Here's my working code:

SELECT DISTINCT 
   i.id, 
   i.dateCreated,
   i.dateBilled,
   i.dateCompleted,
   i.userId, 
   i.type, 
   i.status, 
   i.truck, 
   i.poNumber, 
   i.total,
   i.billtoId, 
   i.shiptoId, 
   i.invoiceNumber, 
   i.loadNumber, 
   SUM(p.amount) as amountpaid,
   c.name as billtoName
FROM `invoices` as i
LEFT JOIN `invoice_payments` as p ON i.id = p.invoice
RIGHT JOIN `companies` as c ON c.id = i.billtoId
GROUP BY i.id, i.invoiceNumber

You can see how i managed to get the SUM from all payments on my invoices with a left join. I'm trying to do the same for i.total, but as soon as i add another LEFT JOIN my calculations come up wrong and the result in amountpaid doubles

  • 写回答

1条回答 默认 最新

  • douji0073 2015-12-30 01:08
    关注

    You can write this query with subqueries in the SELECT statement:

    SELECT id, 
    (SELECT sum(field1) FROM t2 WHERE t2.idfrom1=t1.id) AS firstSum,
    (SELECT sum(field1) FROM t3 WHERE t3.idfrom1=t1.id) AS secondSum,
    (SELECT min(field1) FROM t4 WHERE t4.id=t1.f2 LIMIT 1) AS singleRecord
    FROM t1
    

    This is the idea, you just have to adapt it to your schema.

    edit: updated from the drawing

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题