我想用+=
函数取数据库,但是当我用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