现在的需要的数据如图:从product表中拿到id,name两个字段,从 buy_contract_Item和sale _contract_Item中拿到 quantity,totalMoney这两个字段,再从 buy_contract和sale_contract中拿到 contract_date字段,同时以合同签定时间为查询条件将商品各类的数量和金额sum,最后返回获取结果。表与表的关联关系如图。
后来问了下同事,拿到了返回结果:
一开始就犯了个错误,虽然从 buy_contract_Item和sale _contract_Item获取的信息比较多,但却不能以他们为主表,这是昨天半天还没有结果的主要原因。因为所有后续的这些表都是以商品为主,为商品的买进和卖出服务的。所以这里以商品为主表做查询。 第 一 步 : 从 product 表 中 拿 到 Id , Name 两 个 字 段 ( 其 他 的 字 段 在 后 面 扩 充 ) SELECT id , name FROM product 第 二 步 : 从 buy_contract_item 中 拿 到 productId , SUM ( quantity ) , SUM ( totalMoney ) 这 两 个 字 段 并 按 组 分 类 --productId 为 了 后 面 与 product 表 做 关 联 条 件 的 SELECT productId , SUM ( quantity ) , SUM ( totalMoney ) FROM buy_contract_item GROUP BY productId 第 三 步 : 从 sale_contract_item 中 拿 到 SUM ( quantity ) , SUM ( totalMoney ) 这 两 个 字 段 并 按 组 分 类 SELECT productId , SUM ( quantity ) , SUM ( totalMoney ) FROM sale_contract_item GROUP BY productId 第 四 步 : 对 第 二 步 的 SELECT 语 句 进 行 扩 充 , 联 结 buy_contract : 获 取 SUM ( quantity ) , SUM ( totalMoney ) 和 contract_date SELECT productId , SUM ( quantity ) , SUM ( totalMoney ) , contract_date FROM buy_contract_item a JOIN buy_contract b ON a . contract_id = b . id GROUP BY a . product_id ; 第 五 步 : 添 加 where 查 询 条 件 , 另 外 再 加 上 别 名 SELECT productId , SUM ( quantity ) AS buyQuantity , SUM ( totalMoney ) AS buyTotalMoney , b . contract_date FROM buy_contract_item a JOIN buy_contract b ON a . contract_id = b . id WHERE 1 = 1 and ( b . contract_date >= ‘2015-03-13‘ and b . contract_date <= ‘2015-03-15‘ ) GROUP BY a . product_id ; 第 六 步 : 写 出 sale 的 情 况 和 上 面 类 似 SELECT productId , SUM ( quantity ) AS saleQuantity , SUM ( totalMoney ) AS saleTotalMoney , d . contract_date FROM buy_contract_item c JOIN buy_contract d ON c . contract_id = d . id WHERE 1 = 1 and ( d . contract_date >= ‘2015-03-13‘ and d . contract_date <= ‘2015-03-15‘ ) GROUP BY c . product_id ; 第 一 步 、 第 五 步 、 第 六 步 左 联 结 SELECT t . id , t . name , IFNULL ( buyQuantity , 0 ) AS buyQuantity , IFNULL ( buyTotalMoney , 0 ) AS buyTotalMoney , IFNULL ( saleQuantity , 0 ) AS saleQuantity , IFNULL ( saleTotalMoney , 0 ) AS saleTotalMoney FROM product t LEFT JOIN ( SELECT productId , SUM ( quantity ) AS buyQuantity , SUM ( totalMoney ) AS buyTotalMoney , b . contract_date FROM buy_contract_item a JOIN buy_contract b ON a . contract_id = b . id WHERE 1 = 1 and ( b . contract_date >= ‘2015-03-13‘ and b . contract_date <= ‘2015-03-15‘ ) GROUP BY a . product_id ; ) m ON t . id = m . productId LEFT JOIN ( SELECT productId , SUM ( quantity ) AS saleQuantity , SUM ( totalMoney ) AS saleTotalMoney , d . contract_date FROM buy_contract_item c JOIN buy_contract d ON c . contract_id = d . id WHERE 1 = 1 and ( d . contract_date >= ‘2015-03-13‘ and d . contract_date <= ‘2015-03-15‘ ) GROUP BY c . product_id ; ) n ON t . id = n . productId ORDER BY buyQuantity DESC , saleQuantity DESC 写的中间可能还有错误,但大致思路是这样,复杂的sql语句,可以先写整体框架,然后在框架里不断的细化查询。
一个mysql查询问题
标签:mysql 查询
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://haodehen.cn/did118646