微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

PHP + MySQL:当我从两个表中进行选择时,如何定义我要从哪个表中获取“ id”

如何解决PHP + MySQL:当我从两个表中进行选择时,如何定义我要从哪个表中获取“ id”

|| 我有两个表,每个表都有一个“ id”字段。这是两个表:
news    : id,authorid,datetime,body
authors : id,name
我有这个选择查询
SELECT * FROM news,authors WHERE (news.authorid = authors.id) ORDER BY news.datetime DESC;
然后,在PHP中,我想使用表格新闻的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;
    ,在您的SQL查询中,您可以使用别名:
select table1.id as id_1,table2.id as id_2,...
可以使用别名(而不是列名)从PHP获得列。 就您而言,您将:
SELECT news.id as news_id,news.authorid,news.datetime,news.body,authors.id as author_id,authors.name
FROM news,authors 
WHERE (news.author = authors.id)
ORDER BY news.datetime DESC;
并且,在您的PHP代码中,您将使用别名:
echo $row[\"news_id\"];
echo $row[\"author_id\"];
    ,您应该明确定义要检索的字段,并为模糊的字段添加别名:
select news.id as news_id,authors.id as authors_id,authors WHERE (news.author = authors.id) 
ORDER BY news.datetime DESC authors.name
    ,像SQL中的用户作为语句
select news.id as newsid,news.authorid as newsauthorid,authors.id as authorsid ....
并在PHP中获取为
echo $row[\"newsid\"] ;

//

echo $row[\"authorsid\"] ;
    

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。