JOIN 查询的 Php pdo 结果
我的问题是
我尝试在两个表之间进行简单的 JOIN,这两个表都有 id 字段。我的结果是一个 stdClass 对象,因为我使用 PDO。有谁知道如何区分第一个表的 id 和第二个表的 id?
代码
$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'] ,我需要一个替代方案。
多谢。
My problem is
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?
Code
$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;
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.
Thanks a lot.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您必须为一个表或另一个表中的
id
列指定一个列别名,以使列名不同。这意味着您不能使用“
SELECT *
”,您必须拼写出您想要从该表中获取的所有列名称。如果您希望所有这些列都没有别名,那么至少您仍然可以查询category.*
。顺便说一句,此类问题是避免在每个表中使用“
id
”等通用名称作为主键的一个很好的理由。请使用更具描述性的名称,例如product_id
和category_id
。这样就不会出现列名冲突的问题。You have to give a column alias to the
id
column from one table or the other to make the column names distinct.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 forcategory.*
if you want all those columns without aliasing.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 likeproduct_id
andcategory_id
. Then you won't have the problem of conflicting column names.我使用
This与PDO一起使用
fetch(PDO::FETCH_ASSOC)
I used
This worked with PDO using
fetch(PDO::FETCH_ASSOC)