使用相同的id更新多个表的记录

时间:2014-04-21 05:22:49

标签: mysql sql join insert-update

if(isset($_POST['update_page']))
{
    if($_POST['agent_name']=="" and $_POST['company_name']=="" and $_POST['email']=="")
    {
        $response = asort_form_error("All agent detail fields should be filled");
        extract($_POST);
    }
    else
    {
        $sql = "UPDATE ".TBL_AGENT." SET agent_name = '$_POST[agent_name]' , company_name = '$_POST[company_name]' , email = '$_POST[email]' WHERE agent_id = '{$_GET['id']}'";
        mysql_query($sql,$CN);

        $sql_query = "UPDATE ".TBL_SUBSCRIPTION." SET renewal_date = ( UNIX_TIMESTAMP() + ( '$_POST[subscription_renewal]' * 86400 ) ) WHERE agent_id =  '{$_GET['id']}'";
        mysql_query($sql_query,$CN);

        $response = asort_form_ok("Agent Details Successfully Updated");
        header('Location: subscription.php');
    }
    unset($_POST);
}

我正在尝试使用相同的agent_id更新我的多个数据库表(TBL_AGENTTBL_SUBSCRIPTION)的记录。以上两个查询工作正常。我想用单行写。如何用单行写出这两个$sql$sql_query

3 个答案:

答案 0 :(得分:2)

这应该有效:

"UPDATE ".TBL_AGENT." 
JOIN  ".TBL_SUBSCRIPTION." ON ".TBL_AGENT.".agent_id = ".TBL_SUBSCRIPTION.".agent_id
SET ".TBL_AGENT.".agent_name = '$_POST[agent_name]' , ".TBL_AGENT.".company_name = '$_POST[company_name]' , ".TBL_AGENT.".email = '$_POST[email]',  ".TBL_SUBSCRIPTION.".renewal_date = ( UNIX_TIMESTAMP() + ( '$_POST[subscription_renewal]' * 86400 ) ) 
WHERE ".TBL_AGENT.".agent_id = '{$_GET['id']}';"

答案 1 :(得分:0)

使用JOIN

UPDATE tbl_agent AS a
JOIN tbl_subsription AS s ON a.agent_id = s.agent_id
SET a.agent_name = '$_POST[agent_name]',
    s.renewal_date = ( UNIX_TIMESTAMP() + ( '$_POST[subscription_renewal]' * 86400 ) )
WHERE a.agent_d = '{$_GET['id']}'

答案 2 :(得分:0)

尝试手动执行下面的mysql脚本,然后与代码集成

UPDATE database1.TBL_AGENT a,database2.TBL_SUBSCRIPTION b  SET a.agent_name = <your value> and  a.company_name = <your value> and a.email = <your value> and b.renewal_date = <your value> WHERE a.agent_id = b.agent_id = <your where clause value>