php pdo JOIN查询结果 [英] Php pdo result of JOIN query
问题描述
我尝试在两个都有id字段的表之间做一个简单的JOIN.我的结果是一个stdClass对象,因为我使用的是PDO.有谁知道我该如何区分第一个表的ID和第二个表的ID?
I try to do a simple JOIN between two tables, that both have the id field. My result is an stdClass object, as I use PDO. Does anyone know how can I make a difference between the id of the first table and the id of the second table?
$sql = "SELECT * FROM products AS p
products_categories AS c
WHERE c.id = p.category";
$stmt = $connection->prepare($sql);
$stmt->execute();
$products = array();
while($product = $stmt->fetchObject())
$products[] = $product;
return $products;
如果我尝试使用$ products-> id,它将显示 category 表的ID.如果它是一个数组,我可以使用$ products ['p.id'],我需要一个替代方法.
If I try to use $products->id, it will show me the id of the category table. If it was an array, I could use $products['p.id'] , I need an alternative to this.
非常感谢.
推荐答案
您必须为一个表或另一个表的id
列赋予列别名,以使列名不同.
You have to give a column alias to the id
column from one table or the other to make the column names distinct.
这意味着您不能使用"SELECT *
",您必须拼写要从该表中获取的列名称 all .如果您希望所有这些列都没有别名,那么至少您仍然可以查询category.*
.
This means you can't use "SELECT *
", you have to spell out all the column names you want to fetch from that table. At least you can still query for category.*
if you want all those columns without aliasing.
顺便说一句,这类问题是避免在每个表的主键中使用通用名称(例如"id
")的一个很好的理由.而是使用更具描述性的名称,例如product_id
和category_id
.这样就不会出现列名冲突的问题.
By the way, this sort of problem is a good reason to avoid using a generic name like "id
" for your primary key in every table. Instead use a more descriptive names like product_id
and category_id
. Then you won't have the problem of conflicting column names.
这篇关于php pdo JOIN查询结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!