2010-10-20 97 views
3

我們有三個表:試圖寫一個MySQL連接查詢

p: 

<` 
+-----+-------+-------+--------+--------+ 
| pno | pname | color | weight | city | 
+-----+-------+-------+--------+--------+ 
| p1 | nut | red |  12 | London | 
| p2 | bolt | green |  17 | Paris | 
| p3 | screw | blue |  17 | Rome | 
| p4 | screw | red |  14 | London | 
| p5 | cam | blue |  12 | Paris | 
| p6 | cog | red |  19 | London | 
+-----+-------+-------+--------+--------+ 
` 

s: 


+-----+-------+--------+--------+ 
| sno | sname | status | city | 
+-----+-------+--------+--------+ 
| s1 | Smith |  20 | London | 
| s2 | Jones |  10 | Paris | 
| s3 | Blake |  30 | Paris | 
| s4 | Clark |  20 | London | 
| s5 | Adams |  30 | Athens | 
+-----+-------+--------+--------+ 


sp: 


+-----+-----+-----+ 
| sno | pno | qty | 
+-----+-----+-----+ 
| s1 | p1 | 300 | 
| s1 | p2 | 200 | 
| s1 | p3 | 400 | 
| s1 | p4 | 200 | 
| s1 | p5 | 100 | 
| s1 | p6 | 100 | 
| s2 | p1 | 300 | 
| s2 | p2 | 400 | 
| s3 | p2 | 200 | 
| s4 | p2 | 200 | 
| s4 | p4 | 300 | 
| s4 | p5 | 400 | 
+-----+-----+-----+ 

我們需要完成什麼:讓GRTQ是每個供應商發貨與供應商數量的Si任何種類的綠色和紅色部分的總數量。獲取包含元組的表格,其中GRTQ> 300。以總數量遞增的順序列出結果。

任何好點子?我會盡快發佈一些我的嘗試。

回答

2

這是你的查詢:

SELECT s.sno, SUM(sp.qty) as GRTQ 
FROM s, p, sp 
WHERE s.sno = sp.sno AND p.pno = sp.pno AND (p.color = "red" OR p.color="green") 
GROUP BY s.sno, s.sname 
HAVING GRTQ > 300 
ORDER BY GRTQ ASC; 

The resulting output is: 
+-----+------+ 
| sno | GRTQ | 
+-----+------+ 
| s4 | 500 | 
| s2 | 700 | 
| s1 | 800 | 
+-----+------+ 

你可以自己計算它驗證。

即紅色或綠色的部分是P1,P2,P4,P6

其中:供給僅P2和P4,在分別的200和300,數量

S4。總數= 500

s2分別僅供應p1和p2,數量分別爲300和400。總= 700個

S1提供的所有零部件在這些數量:300 + 200 + 200 + 100 =總計800

2

試試這個:

SELECT 
    s.sno, 
    s.sname, 
    SUM(sp.qty) AS `GRTQ` 
FROM 
    sp 
INNER JOIN 
    s 
ON 
    s.sno = sp.sno 
INNER JOIN 
    p 
ON 
    p.pno = sp.pno 
WHERE 
    (p.color = 'red' or p.color = 'green') 
GROUP BY 
    s.sno, 
    s.sname 
HAVING 
    `GRTQ` > 300 
ORDER BY 
    `GRTQ` ASC 

這是您的樣本數據輸出:

+------+-------+------+ 
| sno | sname | GRTQ | 
+------+-------+------+ 
| s1 | Smith | 800 | 
| s2 | Jones | 1400 | 
+------+-------+------+ 
2 rows in set (0.00 sec) 
+0

這完美的作品,謝謝! – 2010-10-20 10:48:33

+0

您尚未接受任何問題的答案。如果你繼續這樣做,人們會停止幫助你。 – 2010-10-20 20:08:56