无法从PHP执行多表mysql查询

时间:2012-02-01 14:27:34

标签: php mysql mysql-error-1064 multiple-tables

我正在尝试使用table1.column1table2.column3中的值匹配mysql表中的行,然后将每个匹配的table2.column2值复制到table1.column1。下面的查询执行我需要做的事情,但只有当我手动执行它时(通过phpmyadmin)。当我尝试从PHP执行它时,我收到错误Unknown column table1.column1 in 'field list'。这是我的PHP代码:

<?php
mysql_connect($host,$user,$pass);
$db_selected = mysql_select_db($data);

$sql = "UPDATE table1 t1, table2 t2 
        SET t1.column1 = t2.column2 
        WHERE t1.column1 = t2.column3";

$result = mysql_query($sql);

if (!$result) {
  echo mysql_error();
} ?>

我知道mysql连接信息有效,因为我能够执行其他查询。根据我对错误的研究,似乎我可能需要围绕查询的某些部分进行反引号,但经过几次尝试后我无法找出正确的方法。

编辑1 - 这里要求的是真正的查询:

UPDATE wp_mf_custom_groups,wp_mf_posttypes
SET wp_mf_custom_groups.post_type=wp_mf_posttypes.type
WHERE wp_mf_custom_groups.post_type=wp_mf_posttypes.id

输出错误

Unknown column 'wp_mf_custom_groups.post_type' in 'field list'

我刚刚意识到的其他信息可能与之相冲突。在此之前,我还使用以下命名重命名表:

RENAME TABLE wp_mf_module_groups TO wp_mf_custom_groups

也许因为这个表刚刚重命名,所以无法引用它?

2 个答案:

答案 0 :(得分:1)

仅在WHERE

之后向列添加反引号时工作
UPDATE wp_mf_custom_groups,wp_mf_posttypes
SET wp_mf_custom_groups.post_type=wp_mf_posttypes.type
WHERE wp_mf_custom_groups.`post_type=wp_mf_posttypes.id

答案 1 :(得分:0)

如果查询适用于PHPmyadmin,请尝试使用

<?php
$con = mysql_connect($host,$user,$pass) or die('Failed to connect');
$db_selected = mysql_select_db('db_name', $con);

$sql = "UPDATE table1 t1, table2 t2 
    SET t1.column1 = t2.column2 
    WHERE t1.column1 = t2.column3";

$result = mysql_query($sql, $con);

if (!$result) {
  echo mysql_error();
} ?>