MySQL 连接并创建一个新表(?)

标签 mysql

我不确定我是否以正确的方式处理这件事,所以我希望进行现实检查。两张 table ;用户和提要。

+--------+-----------+----------+----------+
| userid | firstname | lastname | username |
+--------+-----------+----------+----------+
|     63 | Chris     | Smith    | csmith   |
|     65 | Roger     | Smith    | rsmith   |
|     66 | Diane     | Smith    | dsmith   |
+--------+-----------+----------+----------+

+-----------+--------+-----------+----------------+
| messageid | userid | contactid | subject        |
+-----------+--------+-----------+----------------+
|         4 | 67     | 63        | Test message 1 |
|         5 | 67     | 63        | Test message 2 |
|         6 | 63     | 67        | Test message 3 |
|         7 | 63     | 67        | Test message 4 |
|         8 | 65     | 66        | Test message 5 |
|         9 | 65     | 66        | Test message 6 |
|        10 | 66     | 65        | Test message 7 |
|        11 | 66     | 65        | Test message 8 |
+-----------+--------+-----------+----------------+

当我在用户页面上生成消息时,我需要在用户 ID(发起者)或 contactid(收件人)中显示消息。将使用用户的用户 ID。但是,我需要显示用户的用户名,而不是他们的用户 ID。因此,这似乎是一个连接语句,我可以将几乎所有这些信息放在一起进行连接。

select a.userid, b.username, a.contactid,
       a.subject, a.message, a.timestamp
from   feed as a,
       users as b
where a.userid=b.userid

结果:

+--------+----------+-----------+----------------+-------------------------------------+
| userid | username | contactid | subject        | message                             |
+--------+----------+-----------+----------------+-------------------------------------+
| 67     | Kimomaru | 63        | Test message 1 | This is a test, hello, hello, hello |
| 67     | Kimomaru | 63        | Test message 2 | This is a test, hello, hello, hello |
| 63     | csmith   | 67        | Test message 3 | This is a test, hello, hello, hello |
+--------+----------+-----------+----------------+-------------------------------------+

但是,我想在 contactid 之后添加一列,用于显示收件人的用户名,该用户名来自用户表中的用户名列。我怎样才能做到这一点?

最佳答案

select a.userid, b.username, a.contactid, 
       c.username, a.subject, a.message, a.timestamp 
from feed as a, users as b , users as c
where a.userid=b.userid and a.contactid=c.userid

关于MySQL 连接并创建一个新表(?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18545426/

相关文章:

android - 直接从 Android 访问 MySQL

Python 和 MySQLdb - 使用 DROP TABLE IF EXISTS 似乎会抛出异常

涉及 'not exists' 的 MYSQL 查询

php - 存储已存储在数据库中的数据的最佳方式?

mysql - 在 MySQL 中创建的 VIEW 使用 SELECT 给出错误的输出

php - Laravel 如何将用户输入与数据库中的数据进行比较

php - 在 MySQL 子查询和 ORDER BY 子查询日期时间中选择多列

c# - MySql和 Entity Framework 导致 "Object reference not set to an instance of an object."

php - 查询获取树上的类别和产品

php - AngularJS $http.get 产品