我想用+=
函數取數據庫,但是當我用group by
這個條件時,最後的結果並不是我想要的,所以請幫我看看我的編碼。Mysql如何通過條件組合?
我有3個表,表1 = t1
:
+-----------+-------------+-------------+-------------+
| ID | areacode | landstatus | pictureid |
+-----------+-------------+-------------+-------------+
| 1 | 1 | 0 | 0 |
| 2 | 1 | 0 | 0 |
| 3 | 1 | 4 | 1 |
| 4 | 1 | 4 | 2 |
| 5 | 1 | 4 | 1 |
| 6 | 1 | 2 | 1 |
| 7 | 1 | 4 | 4 |
| 8 | 1 | 1 | 0 |
| 9 | 2 | 0 | 0 |
| 10 | 2 | 4 | 1 |
+-----------+-------------+-------------+-------------+
表2 = t2
:
+-------+-------------+------------+
| ID | population | other |
+-------+-------------+------------+
| 1 | 10 | 0 |
| 2 | 20 | 0 |
| 3 | 30 | 0 |
| 4 | 40 | 0 |
+-------+-------------+------------+
通常我查詢+-
這樣的:
比方說bid=1
$bid = intval($_GET['bid']);
$queryAP = DB::query("
SELECT t1.*
, t2.population
FROM ".DB::table('t1')." t1
LEFT
JOIN ".DB::table('t2')." t2
ON t1.pictureid = t2.id
WHERE t1.areacode = '$bid'
AND t1.landstatus = 4
");
while($rowAP = DB::fetch($queryAP)) { //search all landstatus == 4
$totalareaP += $rowAP['population'];
}
因此當用戶query
bid=1
時$totalareaP
輸出將是80
。現在我的問題是,如果我想添加一個服務器任務(自動運行查詢,當時間到了)將更新$totalareaP
到t3 where t2.arecode = t3.id
沒有$_GET['bid']
。
表3稱爲:t3
。
+------+------------+-----------+
| ID | population | timesup |
+------+------------+-----------+
| 1 | 0 | timestamp |
| 2 | 0 | timestamp |
+------+------------+-----------+
我嘗試編碼類似:
$queryPPADD = DB::query("SELECT t1.*,t2.population FROM ".DB::table('t1')." t1 LEFT JOIN ".DB::table('t2')." t2 ON (t1.pictureid = t2.id) GROUP BY t1.areacode WHERE t1.landstatus = 4");
while($rowPPADD = DB::fetch($queryPPADD)) { //search all landstatus == 4
$totalareaAAP += $rowPPADD ['population'];
}
當我打印$totalareaAAP
沒有表現出任何價值,我想通過t1.areacode
更新來更新$totalareaAAP
組到t3.areacode WHERE t1.areacode = t3.id
謝謝您。
我沒有看到你的T1連接到你的表2。我的意思是沒有任何外鍵在T2 – learningbyexample
't1.pictureid任何方式= t2.id',當't1.pictureid = t2.id'時,我從't2'查詢'population' –
你初始化$ totalareaAAP了嗎? – learningbyexample