如何创建一个 SQL SELECT 语句,其中一个 table 中有两个字段引用另一个 table 中的相同字段

How do I create a SQL SELECT statement that has two fields in one table referencing the same field in another table

我认为对于那些有更多 SQL 经验的人来说,这是一个简单的答案。我有两个 table。一个 table(网站)中的两个字段引用另一个 (ip_address) 中的一个字段。我在创建将打印以下输出的 SELECT 命令时遇到问题:

MariaDB [test]> select * from website;
+----+-----------+--------------+----------------+
| id | node_name | primary_host | secondary_host |
+----+-----------+--------------+----------------+
|  1 | site1     |            1 |              2 |
|  2 | site2     |            3 |              4 |
+----+-----------+--------------+----------------+
2 rows in set (0.00 sec)

MariaDB [test]> select * from ip_address;
+----+-------------+
| id | ip          |
+----+-------------+
|  1 | 192.168.1.1 |
|  2 | 192.168.1.2 |
|  3 | 192.168.1.3 |
|  4 | 192.168.1.4 |
+----+-------------+
4 rows in set (0.00 sec)

需要输出:

+-----------+-------------+-------------+
| node_name | ip          | ip          |
+-----------+-------------+-------------+
| site1     | 192.168.1.1 | 192.168.1.2 |
| site2     | 192.168.1.3 | 192.168.1.4 |
+-----------+-------------+-------------+
2 rows in set (0.00 sec)

我认为这应该可以解决您的问题。

select v1.node_name, v2.ip, v3.ip 
from website v1 
left join ip_address v2 on v1.primary_host = v2.id 
left join ip_address v3 on v1.secondary_host = v3.id