2011-04-13 36 views
1

我有两个表,每个表都有一个“id”字段。这里有两个表:PHP + MySQL:当我从两个表中选择时,如何定义我想从哪个表中获取“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 
} 

回答

3

给他们别名

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; 
+0

谢谢! +1因为星号 – 2011-04-13 12:00:27

+0

尽管如此,你不应该真的使用星号,具体来说你正在检索哪些信息。在以后的日子里,表格模式可能会增长,然后你会选择很多额外的列没有很好的理由... – philm 2011-04-13 12:26:43

+0

@philm你是对的。我的技术主管(他坐在我的对面)一直说这是一个咒语,这就是为什么我包括这两个例子:) – JohnP 2011-04-13 12:28:18

3

你的SQL查询,您可以使用别名:

select table1.id as id_1, table2.id as id_2, ... 

列会可以使用别名从PHP获得,而不是名称s的列。


在你的情况,你必须:

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"]; 
+0

谢谢!我更喜欢JohnP的回答,因为使用了asterix。但是:+1 – 2011-04-13 12:01:15

+0

不客气:-) *(没问题^^)* – 2011-04-13 12:02:51

0

你应该明确地定义你的字段想要检索并混淆隐含的内容:

select news.id as news_id, news.authorid, news.datetime, news.body, 
    authors.id as authors_id, authors.name 
FROM news, authors WHERE (news.author = authors.id) 
ORDER BY news.datetime DESC authors.name 
0

user as stat EMENT在SQL像

select news.id as newsid, news.authorid as newsauthorid, authors.id as authorsid .... 

,并在PHP中获得尽可能

echo $row["newsid"] ; 

// 

echo $row["authorsid"] ; 
相关问题