简体   繁体   English

从两个单独的表中选择数据

[英]SELECT Data from Two Separate Tables

I have two separate tables. 我有两个单独的表。 I need to SELECT the avatar from the user table, WHERE the username equals from on the comments table. 我需要从用户表,其中的用户名 comments表等于选择的化身 I am trying to create a comment system that displays the user's avatar next to their message. 我正在尝试创建一个注释系统,以在用户的​​消息旁边显示用户的头像。

Comments - ID|Username|From|Timestamp|Message 注释 -ID |用户名|发件人|时间戳|消息
User - ID|Username|Avatar 用户 -ID |用户名|头像

$fetchto=mysql_fetch_object(mysql_query("SELECT * FROM user WHERE username='$variable'"));

I think I could display the URL to the avatar using $fetchto->avatar if I had a variable that would pull the avatar of the member making the comment from the user table. 我想我可以使用$ fetchto-> avatar显示指向化身的URL,如果我有一个变量可以从用户表中提取发表评论的成员的化身。

First off your database isn't properly normalized . 首先,您的数据库未正确规范化 The comments should refer to the User by UserId , not by Username . 注释应通过UserId而不是Username引用User Once you've fixed that: 解决此问题后:

select * from Comments c
join User u on u.ID = c.UserId

Until then: 直到那时:

select * from Comments c
join User u on u.UserName = c.UserName

Also, please stop using the mysql_ family of functions - they're deprecated . 另外,请停止使用mysql_系列功能- 已弃用

Your query needs to have a simple join, something like this: 您的查询需要有一个简单的联接,如下所示:

SELECT c.*, u.avatar
FROM comments AS c
JOIN user AS u ON c.username = a.username

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM