【发布时间】:2011-11-15 11:18:06
【问题描述】:
我有一个问题:
SELECT * FROM categorys
LEFT JOIN category_info ON categorys.cat_id=category_info.cat_id
WHERE `cat_name` = 'aname'
ORDER BY `cat_order`
当我在 phpMyAdmin 中运行它时,无论第二个表中是否存在匹配项,我都会返回一个 cat_id。
但是,当我在我的 PHP 代码中运行此查询时,我得到一个空白的 cat_id,如 print_r() 所示:
数组 ( [cat_id] => [cat_name] => 浴室 [type] => main [cat_order] => 99 [cat_img] => [显示] => 1 [已删除] => 0 [desc_id] => [desc] => [文本] => )
当查询完全一样时,为什么会有不同的结果?
编辑: 我的 PHP 代码:
$getcatidsql = "SELECT * FROM categorys
LEFT JOIN category_info ON categorys.cat_id=category_info.cat_id
WHERE `cat_name` = '{$cname}'
ORDER BY `cat_order";
$getcatidresult = $db->query( $getcatidsql );
$catdata = $db->fetchRow( $getcatidresult );
function query() {
$this->query_total++;
if (func_num_args() == 1) {
$sql = func_get_arg(0);
} else {
$args = func_get_args();
for ($i=1;$i<count($args);$i++) if (!is_numeric($args[$i])) $args[$i] = '"'.mysql_real_escape_string($args[$i]).'"';
$sql = vsprintf(array_shift($args),$args);
}
if ($result = mysql_query($sql,$this->db_connection)) {
return $result;
} else {
$this->dberror( $this->db_connection, $sql );
}
}
function fetchRow($result,$type=MYSQL_ASSOC)
{
if($result)
$row = mysql_fetch_array($result,$type);
return $row;
}
【问题讨论】:
-
也许您使用不同的数据库?显示你的 php 代码
-
不是同一个数据库。我对为什么 PHP 中的查询出错感到困惑,所以我使用 phpMyAdmin 来调试它。就在那时,我看到查询按预期工作。
-
仅供参考,
category的复数形式是categories,而不是categorys。 -
我唯一的猜测是,因为数据不存在,LEFT JOIN 为 category_info(表 2)中的所有行设置了 NULL,所以 category_info.cat_id 的 NULL 可能正在替换类别中的内容。 cat_id?
-
是的:您正在从
categorys和category_info中选择 *。他们都有一个cat_id列。所以你会得到两个cat_id列。问题是:当您使用的 SQL 库/驱动程序在 SELECT 列表中遇到两个具有相同名称的列时,它会做什么?看起来它可能会用第二个覆盖它遇到的第一个......如果您使用显式 SELECT 列表,指定categorys.cat_id并且 not 引入category_info.cat_id会发生什么?
标签: php mysql database join phpmyadmin