[英]MySQL join results different in PHP?
我有一个问题:
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] =>浴室[类型] =>主[cat_order] => 99 [cat_img] => [显示] => 1 [删除] => 0 [desc_id] => [desc] => [text] =>)
当查询完全相同时,为什么会有不同的结果?
编辑:我的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;
}
我认为你不能使用select *(也因为两个表中的列名相同),而是根据需要选择准确的字段
select table_name.field, table_name.field2, other_table_name.field1
..并且你将得到PHP代码和phpmyadmin的正确结果
我认为这是因为'cat_id'在两个表中都是相同的字段名=>结果数组中的相同索引。 尝试修改如下的查询:“从classes中选择categorys.cat_id AS类别.....”
你是从categorys
和category_info
选择*。 它们都有一个cat_id
列。 所以你会得到两个cat_id
列。
问题是:当您在SELECT列表中遇到两个具有相同名称的列时,您正在使用的SQL库/驱动程序是做什么的?
看起来它可能会覆盖第二个遇到的第一个......如果使用显式SELECT列表,指定categorys.cat_id
而不引入category_info.cat_id
什么?
当你说
当我在phpMyAdmin中运行它时,我得到了一个cat_id
你是说你为cat_id获得了一个VALUE还是你把它变为NULL? 因为这是你用php得到的,cat_id的NULL值(正如你在print_r中看到的那样,它仍然出现在那里)。
如果您不希望从该categorys
中没有现有行的category_info
获取行,则必须使用RIGHT JOIN而不是LEFT JOIN。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.