mysql join 2表过滤结果

wlzqhblo  于 2021-06-15  发布在  Mysql
关注(0)|答案(1)|浏览(341)

我有两个表用户和转介。
这是两个表的结构。
推荐表

|    Column    |
----------------
| ref_id       |
| from_user_id |
| to_user_id   | 
| ref_name     |    
| ref_phone    |    
| ref_email    |        
| ref_note     |

用户表

|    Column    |
----------------
| user_id         |
| user_name       |
| user_first_name |
| user_last_name  |
| user_email      |
| user_phone      |

我有两个部分,用户可以看到收到和发送的推荐。
在received referral部分中,我如何从users表中获取第一个\u名称和最后一个\u名称,该表加入referral表中的from \u user \u id。
到目前为止,我对ReceivedReferral提出了这个查询,它可以得到预期的结果集。但是如何从referror table从用户id中获取users表firstname和lastname呢

SELECT users.user_id, users.user_name, users.user_firstname, users.user_lastname, referral.ref_name, referral.ref_phone, referral.ref_email, referral.ref_note
FROM referral JOIN users 
ON referral.to_user_id = users.user_id 
WHERE referral.to_user_id = (logged in user id)

类似地,在“已发送引用”部分中,如何从\u user\u id键获取加入用户和引用表的用户名和姓氏

SELECT users.user_id, users.user_name, users.user_firstname, users.user_lastname
            FROM referral JOIN users 
            ON referral.from_user_id = users.user_id
            WHERE referral.from_user_id = (logged in user id)

任何帮助都将不胜感激。

vu8f3i0k

vu8f3i0k1#

我想您需要在users表上有两个连接:

select r.ref_name, r.ref_phone, r.ref_email, r.ref_note,
    uf.user_id as from_user_id, uf.user_name as from_user_name, uf.user_firstname as from_user_firstname, uf.user_lastname as from_user_lastname, 
    ut.user_id as to_user_id,   ut.user_name as to_user_name,   ut.user_firstname as to_user_firstname,   ut.user_lastname as to_user_lastname
from referral r
inner join users ut on r.to_user_id   = ut.user_id 
inner join users uf on r.from_user_id = uf.user_id
where r.to_user_id = ?

相关问题