简单 SQL 一次查询两个表中的 select 数据
Simple SQL Query to select data from two tables at once
我在 node js 中为我的聊天应用程序准备了两个表。
TABLE 用户 :
- id (PK, AI)
- username
- useremail
- userpass
TABLE消息:
- mess_id (PK, AI)
- mess_to (FK - users.id)
- mess_from (FK - users.id)
- mess_txt
- timestamp
当用户登录时,我想检索那些向当前用户发送消息的人以及当前用户向他们发送消息的人的用户名。
目前我试过的查询是
SELECT username FROM users JOIN messages ON users.id = messages.mess_to OR users.id = messages.mess_from WHERE users.id = 1
The above query returns the username of the current user , from each fields where he sent messages or he received the messages, and what I want is to get the names of the users who sent him messages and who got messages from this user.
我会使用 UNION 子查询来获取与当前用户进行过对话的用户的 ID。然后加入 users
table.
select u.*
from (
select mess_to as user_id from messages where mess_from = 1
union
select mess_from as user_id from messages where mess_to = 1
) sub
join users u on u.id = sub.user_id
我在 node js 中为我的聊天应用程序准备了两个表。
TABLE 用户 :
- id (PK, AI)
- username
- useremail
- userpass
TABLE消息:
- mess_id (PK, AI)
- mess_to (FK - users.id)
- mess_from (FK - users.id)
- mess_txt
- timestamp
当用户登录时,我想检索那些向当前用户发送消息的人以及当前用户向他们发送消息的人的用户名。
目前我试过的查询是
SELECT username FROM users JOIN messages ON users.id = messages.mess_to OR users.id = messages.mess_from WHERE users.id = 1
The above query returns the username of the current user , from each fields where he sent messages or he received the messages, and what I want is to get the names of the users who sent him messages and who got messages from this user.
我会使用 UNION 子查询来获取与当前用户进行过对话的用户的 ID。然后加入 users
table.
select u.*
from (
select mess_to as user_id from messages where mess_from = 1
union
select mess_from as user_id from messages where mess_to = 1
) sub
join users u on u.id = sub.user_id