gpt4 book ai didi

php - 如何显示两个不同表中具有相同名称的列?

转载 作者:可可西里 更新时间:2023-11-01 00:10:32 27 4
gpt4 key购买 nike

我从两个表中进行了 SQL 查询。一切正常,但问题是这两个表具有相同的字段名称,在我不知道如何正确显示它们之后,如何判断 $data['aaa'] 来自表 1 和相同的 $data['aaa '] 来自表 2

这是我的 SQL 查询:

    $query_str = "SELECT 
cm.id,
cm.global_category_id,
cm.num,
cm.menu_lv,
cm.menu_ru,
cm.menu_en,
u.id,
u.menu_lv,
u.menu_ru,
u.menu_en
FROM products_category cm, products_global_category u
WHERE cm.global_category_id = u.id
";

和显示数据

<? foreach ($sub_category_list as $line) : ?>
<tr>
<td><?=$line['menu_lv']?></td> <---- here I want to display data from products_global_category u
<td><?=$line['sub_menu_lv']?></td> <---- products_category cm
<td><?=$line['sub_menu_ru']?></td> <---- products_category cm
<td><?=$line['sub_menu_en']?></td> <---- products_category cm
</tr>
<? endforeach; ?>

最佳答案

作为一种解决方案,您可以更改 SQL 查询,为具有相同名称的字段提供别名。

例如:

SELECT somefield AS othername FROM table.

在这种情况下,somefield 字段将通过别名 othername 可用。

在你的情况下:

$query_str = "SELECT 
cm.id AS cm_id,
cm.global_category_id,
cm.num,
cm.menu_lv AS cm_menulv,
cm.menu_ru AS cm_menuru,
cm.menu_en AS cm.menuen,
u.id as u_id,
u.menu_lv AS u_menulv,
u.menu_ru AS u_menuru,
u.menu_en AS u_menuen
FROM products_category cm, products_global_category u
WHERE cm.global_category_id = u.id
";

然后在您的 PHP 中:

$line['u_menulv'] //Access field menu_lv from products_global_category table
$line['cm_menulv'] //Access field menu_lv from products_category table

编辑mysql_fetch_array documentation page :

If two or more columns of the result have the same field names, the last column will take precedence. To access the other column(s) of the same name, you must use the numeric index of the column or make an alias for the column. For aliased columns, you cannot access the contents with the original column name.

换句话说,要么创建如上所示的别名,要么通过数组的数字索引访问字段。

关于php - 如何显示两个不同表中具有相同名称的列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8631380/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com