从同一行中第一列的值旁边选择第二列的值

Selecting values from second column alongside the values from first column in the same row

我正在尝试获取与第二列中的值匹配的值。例如,我想仅通过 ID 就知道谁是 Bill Gates 的发件人。

我有两个表,

*users* table
| user_ID  | Full_name      |
| -------- | -------------- |
| 1        | Steve Jobs     |
| 2        | Bill Gates     |
| 3        | Elon Musk      |

*relationships* table (with both column foreign keys)
| user_sender  | user_receiver  |
| ------------ | -------------- |
| 1            | 2              |
| 3            | 1              |
| 3            | 2              |

我想select基于“user_receiver”列匹配“user_sender”列中的值

比如我想知道user_sender谁是2 输出:

|              |                |
| ------------ | -------------- |
| 1            | 2              |
| 3            | 2              |

您需要连接表格和select您想要的行

您可以通过别名访问这两个表的所有列

SELECT u.user_ID  , u.Full_name,r.user_receiver 
 FROM users u JOIN 
relationships r ON u.user_ID = r.user_sender
WHERE r.user_receiver = 2

如果要根据名称查找,则加入到用户的关系。

SELECT 
  rel.user_sender
, rel.user_receiver
-- , sender.Full_name AS sender_name
-- , receiver.Full_name AS receiver_name
FROM relationships AS rel
JOIN users AS sender ON sender.user_ID = rel.user_sender
JOIN users As receiver ON receiver.user_ID = rel.user_receiver
WHERE receiver.Full_name = 'Bill Gates' 

如果您已经知道 user_receiver 号码,并且只需要 ID 的

SELECT *
FROM relationships
WHERE user_receiver = 2