有3個表格,A、B、C
A表結構 (訂單表)
id
B表結構 (訂單產品表,一個訂單有多個產品)
id
Aid (A表id的外鍵)
chanpinid (倉庫產品的id)
shuliang (數量)
C表格 (倉庫表,B表的訂單產品,都來自倉庫!)
id
現在想查A的訂單記錄數:工時費 + 產品數量*單價 > 100塊的。如何寫sql??
我寫的不成功。如下:
select distinct(A.id) from ((A JOIN B ON A.id=B.Aid ) inner join C on B.chanpinid=C.id GROUP BY Ai.d HAVING SUM(C.danjia*B.shuliang+A.workfee) >100
就好比:訂購一個面包,有手工費,然後還有原料:面粉3克、鹽巴1克,糖2克等,面粉等原材料價格保存在倉庫表中的。
現在想知道: 手工費+面粉3克*價格 +鹽巴1克*價格 +糖2克*價格 >100的面包,有幾個!!
標准答案:
create table Table_A (
id int,
Workfee int
)
create table Table_B (
id int,
Aid int,
chanpinid int ,
shuliang int
)
create table Table_C (
id int,
danjia int
);
insert into Table_A values(100,30);
insert into Table_A values(200,20);
insert into Table_B values(1,100,10,10);
insert into Table_B values(2,100,11,5);
insert into Table_B values(3,100,12,5);
insert into Table_B values(4,200,10,2);
insert into Table_B values(5,200,11,2);
insert into Table_C values(10,5);
insert into Table_C values(11,1);
insert into Table_C values(12,20);
SQL:
select a.id,SUM(Workfee + d.shangpinjiage ) from Table_A a,
(select Aid,SUM(c.danjia * b.shuliang) shangpinjiage
from Table_B b,Table_C c
where b.chanpinid = c.id and b.chanpinid =c.id
group by Aid) d
where a.id = d.Aid
group by a.id
having SUM(Workfee + d.shangpinjiage ) > 100