我有一个php代码,它汇总了来自同一数据库的两个不同表的同一列的值,并将其存储在变量中。代码如下:
$sql = 'SELECT
(SELECT SUM( time_spent )
FROM '.TICKET_RESPONSE_TABLE.'
WHERE ticket_id='.db_input($id).')
+(SELECT SUM( time_spent )
FROM '.TICKET_NOTE_TABLE.'
WHERE ticket_id='.db_input($id).')
AS total_time';
$result = db_query($sql);
$cursor = mysql_fetch_row($result);
$total_time = $cursor[0];
现在,我想要更新同一数据库的另一个表中的列,其值存储在变量$ total_time中。请帮助我。
答案 0 :(得分:2)
您可以直接更新,而不是使用变量。
$sql = 'UPDATE *tablename*
SET *columname* =
(SELECT SUM( time_spent )
FROM '.TICKET_RESPONSE_TABLE.'
WHERE ticket_id='.db_input($id).')
+(SELECT SUM( time_spent )
FROM '.TICKET_NOTE_TABLE.'
WHERE ticket_id='.db_input($id).')';
$result = db_query($sql);
或像这样的后记:
$sql = 'SELECT
(SELECT SUM( time_spent )
FROM '.TICKET_RESPONSE_TABLE.'
WHERE ticket_id='.db_input($id).')
+(SELECT SUM( time_spent )
FROM '.TICKET_NOTE_TABLE.'
WHERE ticket_id='.db_input($id).')
AS total_time';
$result = db_query($sql);
$cursor = mysql_fetch_row($result);
$total_time = $cursor[0];
$sql = 'SUPDATE *tablename*
SET *columname* = ' . $total_time
$result = db_query($sql);
答案 1 :(得分:0)
您可以进行子选择:
UPDATE table1 t1
SET t1.val1 =
(SELECT val FROM table2 t2 WHERE t2.id = t1.t2_id )
WHERE t1.val1 = '';
答案 2 :(得分:0)
为什么不呢 $ sql =“INSERT INTO其他表SET field_name = $ total_time”; $ result = db_query($ sql);