从 PHP 检索 MYSQL Join 值

发布于 2024-08-09 14:31:57 字数 419 浏览 6 评论 0原文

我有两个或多个表,它们在同一列名下保存值。现在,当我连接这两个表时,列名保持不变。在 PHP 中检索这些值 ($row['name']) 时,我遇到了问题,因为“name”列被使用了两次。

是否有任何可能的方法来分隔查询中的这两列?

  SELECT *
    FROM stories s
    JOIN authors a ON a.id = s.authorid

故事 id、名称、内容、日期

作者 id,名称,日期

当我加入这两个时,我得到一张具有相似“名称”列的表。

是否有办法将两个表分开,以便作者表前面有一个前缀?例如,authors_name /authors_*

I have two or more tables which hold values under the same column name. Now when I join these two tables the column names stay the same. When retrieving these values in PHP ($row['name']) I encounter problems since the column 'name' is used twice.

Are there any possible means of separating these two columns inside the query?

  SELECT *
    FROM stories s
    JOIN authors a ON a.id = s.authorid

Table stories
id, name, content, date

Table authors
id, name, date

When i join these two i get one table with similar 'name' columns.

Is there anyway to separate the two tables so the author table has a prefix in front of it? E.g. authors_name /authors_*

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

ι不睡觉的鱼゛ 2024-08-16 14:31:57

是的,以这种方式更改 SQL:

SELECT 
  s.Id as StoryId, 
  s.Name as StoryName,
  a.Id as AuthorId, 
  a.Name as AthorName,
FROM stories s
JOIN authors a ON a.id = s.authorid

然后在 php 中,使用 StoryId、StoryName、AuthorId 和 AthorName 而不是 Id 或 Name。

希望对您有帮助。

Yes, change your SQL this way :

SELECT 
  s.Id as StoryId, 
  s.Name as StoryName,
  a.Id as AuthorId, 
  a.Name as AthorName,
FROM stories s
JOIN authors a ON a.id = s.authorid

Then in php, use StoryId, StoryName, AuthorId and AthorName instead of Id or Name.

Hope it helps you.

他是夢罘是命 2024-08-16 14:31:57

是的,有!

SELECT *, stories.name AS s_name, authors.name AS a_name
FROM stories s
JOIN authors a ON a.id = s.authorid

现在你就得到了它。所有字段加上两个额外字段! ;)

希望有帮助。

Yes there is!

SELECT *, stories.name AS s_name, authors.name AS a_name
FROM stories s
JOIN authors a ON a.id = s.authorid

And there you have it. All fields plus two extra! ;)

Hope it helps.

病毒体 2024-08-16 14:31:57

抱歉,您实际上无法在字段级别上添加前缀,但如果您可以调用 2 个查询,只需使用

SELECT s.*
FROM stories s
JOIN authors a ON a.id = s.authorid

结果集将仅包含故事字段,您可以像通常使用 php 一样使用这些字段。然后对作者再次做同样的事情。

Sorry you can't really do prefixing on a field level, but if you can call 2 queries, just use

SELECT s.*
FROM stories s
JOIN authors a ON a.id = s.authorid

The result set will only contain stories fields and you can use the fields as you normally would with php. Then just do the same again for authors.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文