2015-02-08 62 views
-1

我有加入小問題。我有4張桌子。多個內部聯接與哪裏條款 - 4表

as_ticmat TBL加盟as_mat TBL這樣我就可以得到名來自列as_mat TBL同樣的事情
as_sertic TBL加盟as_ser TBL但只有一個條件。這是從as_ticmat TBL的tic_id柱必須等於1,以及從as_sertic TBL的tic_id柱必須等於1

這裏是我的表

mysql> TBL: as_ticmat; 
+--------------+---------+---------+-----------+ 
| ticmat_id | mat_id | tic_id | matprice | 
+--------------+---------+---------+-----------+ 
|   1 |  1 |  1 |  20.00 | 
|   2 |  2 |  1 |  30.00 | 
|   3 |  3 |  4 | 640.00 | 
|   4 |  4 |  4 | 500.00 | 
+--------------+---------+---------+-----------+ 

mysql> TBL: as_mat; 
+-----------+-------------------+ 
| mat_id | name    | 
+-----------+-------------------+ 
|   1 | XXXX - XXXXX - XX | 
|   2 | XXXX - XXXXX - XX | 
|   3 | XXXX - XXXXX - XX | 
|   4 | XXXX - XXXXX - XX | 
+-----------+-------------------+ 

mysql> TBL: as_sertic; 
+--------------+---------+---------+---------+---------+ 
| sertic_id | tic_id | ser_id | mec_id | rate | 
+--------------+---------+---------+---------+---------+ 
|   1 |  1 |  2 |  4 | 500.00 | 
|   2 |  1 |  3 |  4 | 1000.00 | 
|   3 |  4 |  4 |  4 | 420.00 | 
|   4 |  4 |  5 |  4 | 420.00 | 
+--------------+---------+---------+---------+---------+ 

mysql> TBL: as_ser; 
+------------+----------+--------+ 
| ser_id  | name  | price | 
+------------+----------+--------+ 
|   1 | XXX XXXX | 50.00 | 
|   2 | XXX XXXX | 50.00 | 
|   3 | XXX XXXX | 250.00 | 
|   4 | XXX XXXX | 210.00 | 
|   5 | XXX XXXX | 210.00 | 
+------------+----------+--------+ 

這是我的查詢。

SELECT `as_ticmat`.`tickmat_id`, 
     `as_ticmat`.`mate_id`, 
     `as_ticmat`.`mateprice`, 
     `as_sertic`.`sertic_id`, 
     `as_sertic`.`ser_id`, 

SUM  (as_tictmat.matprice`) AS `mat` 
SUM  (as_sertic.rate)  AS `ser` 
FROM  `as_ticmat` 
INNER JOIN `as_sertic` 
ON   `as_sertic`.`ser_id` = `as_ser`.`ser_id` 
INNER JOIN `as_mate` 
ON   `as_ticmat`.`mat_id` = `as_mat`.`mat_id` 
WHERE  `tic_id` = 1 
+0

你說你有一個小問題,但我沒有看到任何問題? – jpw 2015-02-08 17:42:14

+0

對不起,忘了提我的問題。有sql錯誤..我只是不能完成 – 2015-02-08 17:44:54

+0

這個查詢是否需要一個'group by'子句?還是滿足於一行結果? – 2015-02-08 17:56:57

回答

1

您的查詢有幾個拼寫錯誤,缺少逗號,你也從未加入as_ser表。我認爲,改正後的查詢應該是這樣的:

SELECT as_ticmat.ticmat_id, 
     as_ticmat.mat_id, 
     as_ticmat.matprice, 
     as_sertic.sertic_id, 
     as_sertic.ser_id, 
     SUM(as_ticmat.matprice) AS mat, 
     SUM(as_sertic.rate)  AS ser 
FROM  as_ticmat  
INNER JOIN as_sertic 
ON   as_sertic.ser_id = as_ticmat.tic_id 
INNER JOIN as_ser 
ON   as_sertic.ser_id = as_ser.ser_id 
INNER JOIN as_mat 
ON   as_ticmat.mat_id = as_mat.mat_id 
WHERE  as_ticmat.tic_id = 1 

所有這些錯誤很容易從出現的錯誤信息找到...

對於大多數SQL數據庫,您還需要一個group by條款的因爲你正在使用一個聚合函數(MySQL是一個例外,因爲它不需要group by子句,但是如果你分組數據,你不會得到結果),在這種情況下你應該添加

GROUP BY 
     as_ticmat.ticmat_id, 
     as_ticmat.mat_id, 
     as_ticmat.matprice, 
     as_sertic.sertic_id, 
     as_sertic.ser_id 

在查詢結束時年。

+0

哦,我沒有看到,甚至認爲我已經檢查了幾次查詢。感謝「JPW」我會檢查查詢希望它的工作.. – 2015-02-08 17:55:11

+1

感謝pro..it的作品。這是一些錯別字,我討厭... :) – 2015-02-08 20:05:02