gpt4 book ai didi

PHP + MySQL : When I select from two tables, 如何定义我要从哪个表中取 "id"

转载 作者:行者123 更新时间:2023-11-29 04:12:51 25 4
gpt4 key购买 nike

我有两个表,每个表都有一个“id”字段。这是两个表:

news    : id, authorid, datetime, body
authors : id, name

我有这个选择查询:

SELECT * FROM news, authors WHERE (news.authorid = authors.id) ORDER BY news.datetime DESC;

然后,在 PHP 中,我想使用表 news 的 id。我有这段代码:

while ($row = mysql_fetch_array($result)) 
{
// I want to take news.id, but it gives an error:
echo $row["news.id"]; // error: "Undefined index: news.id"

// And when I write only "id", it takes it of authors.
echo $row["id"]; // this id is authors.id, but I want news.id
}

最佳答案

给他们起个别名

SELECT news.id AS news_id FROM news, authors WHERE (news.author = authors.id) ORDER BY news.datetime DESC;

或者

SELECT *, news.id AS news_id FROM news, authors WHERE (news.author = authors.id) ORDER BY news.datetime DESC;

关于PHP + MySQL : When I select from two tables, 如何定义我要从哪个表中取 "id",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5648758/

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