使用表从SQL查询循环

时间:2016-08-24 12:52:30

标签: mysql sql

我有一张这样的表

SparePart

+-------------+------------------------+--------+---------+
| sparePartID | name                   | price  | modelID |
+-------------+------------------------+--------+---------+
| 12V         | Preheat Start Relay    |   1470 | WADR40E |
| 12V.        | Instrument Assembly    |   1290 | WADR40E |
| 12V..       | Motor Module(360)      |  17810 | WADR40E |
| 40CC        | HST  Assembly          | 264840 | WADR40E |
| 4L88        | Oil Filter Core        |   1200 | WADR40E |
| 4L88.       | Diesel oil Filter Core |    260 | WADR40E |
| 4SB1490     | Belt                   |   9930 | WADR40E |
| 50*2.65     | Axeal -O Ring          |     80 | WADR40E |
| 60*85*10    | Oil seal               |   1180 | WADR40E |
| 9J-5-1605   | Joint Belt             |   8960 | WADR40E |
+-------------+------------------------+--------+---------+

和MainStock

+-------------+-----+------------+-------------+
| originalQty | qty | shipmentID | sparePartID |
+-------------+-----+------------+-------------+
|          20 |  20 | RnsttFOY   | RT125-03001 |
|          10 |  10 | SHPMT78    | RT125-03001 |
|           8 |   8 | RH987ho    | 12V         |
|           0 |   0 | RH987ho    | 4SB1490     |
+-------------+-----+------------+-------------+

所以我使用这样的查询来计算所有货物的所有库存

SELECT SUM(`qty`) FROM MainStock WHERE sparePartID='RT125-03001';

我想循环遍历SparePart表中的每个sparePartID并获取表结果。我试过这样的事情。

SELECT SUM(`qty`)
    -> FROM MainStock, SparePart
    -> WHERE sparePartID=SparePart.sparePartID;

但我收到一条消息说

ERROR 1052 (23000): Column 'sparePartID' in where clause is ambiguous

那我怎么能做到这一点?

3 个答案:

答案 0 :(得分:3)

你真的不需要一个循环,只需一个简单的连接和GROUP BY

SELECT SP.sparePartID, SUM(qty) as qty
FROM SparePart SP
LEFT JOIN MainStock MS
    ON SP.sparePartID = MS.sparePartID
GROUP BY SP.sparePartID

答案 1 :(得分:1)

您必须为每个列添加表名称,或者更好地使用表的别名:

SELECT SUM(`qty`)
     FROM MainStock ms, SparePart sp
     WHERE ms.sparePartID=sp.sparePartID;
     Group by sp.sparePartID

答案 2 :(得分:0)

您收到错误,因为两个表都包含backupPartId列。所以我们也要给表名以避免歧义。

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="demoApp" ng-controller="mainController as ctrl">

  <!-- with a directive that scans inner-html -->
  <h2>inner text with directive</h2>
  <p inner-style>
  Green.
  </p>
   <p inner-style>
    Red.
  </p>
  
  <!--I wouldn't do  the above, instead use a model. Something like this <br/>-->
  <h2>same with a model</h2>
  <p ng-class="ctrl.data.firstModel.class">
    {{ctrl.data.firstModel.text}}
  </p>
  <p ng-class="ctrl.data.secondModel.class">
    {{ctrl.data.secondModel.text}}
  </p>
</div>