gpt4 book ai didi

sql - 如何在 MySQL 中连接具有不同行数的两个表?

转载 作者:可可西里 更新时间:2023-11-01 07:47:05 24 4
gpt4 key购买 nike

我有两个要连接的表。

表_A:

+-----------+-----------+---------+
| row_id | category | val_1 |
+-----------+-----------+---------+
| 1067 | cat1 | 6.5 |
| 2666 | test | 6.5 |
| 2710 | cat1 | 2.1 |
| 2710 | test | 7.1 |
| 2767 | test | 3 |
| 71142 | cat1 | 5 |
| 50666 | other | 6.5 |
| 71142 | other | 1 |
| 345342 | cat1 | 6.5 |
| 345342 | test | 2.8 |
+-----------+-----------+---------+

表_B:

+-----------+-----------+
| row_id | val_2 |
+-----------+-----------+
| 1067 | 2.0 |
| 2666 | 9 |
| 2701 | 2.2 |
| 2708 | 1 |
| 2709 | 6.5 |
| 2710 | 5.2 |
| 2765 | 6.5 |
| 2766 | 15 |
| 2767 | 8 |
| 71142 | 5 |
| 2783 | 4.5 |
| 50666 | 6.5 |
| 101588 | 9 |
| 101588 | 3 |
| 3452 | 8.0 |
| 23422 | 5 |
| 345342 | 6.5 |
+-----------+-----------+

结果表:

+-----------+-----------+-----------+------------+
| row_id | val_2 | val_1 | category |
+-----------+-----------+-----------+------------+
| 1067 | 2.0 | 6.5 | cat1 |
| 2666 | 9 | 6.5 | test |
| 2701 | 2.2 | 2.2 | NULL |
| 2708 | 1 | 1 | NULL |
| 2709 | 6.5 | 1 | NULL |
| 2710 | 5.2 | 2.1 | cat1 |
| 2710 | 5.2 | 7.1 | test |
| 2765 | 6.5 | 1 | NULL |
| 2766 | 15 | 1 | NULL |
| 2767 | 8 | 3 | test |
| 71142 | 5 | 5 | cat1 |
| 71142 | 5 | 1 | other |
| 2783 | 4.5 | 1 | NULL |
| 50666 | 6.5 | 6.5 | other |
| 101588 | 9 | 1 | NULL |
| 101588 | 3 | 1 | NULL |
| 3452 | 8.0 | 1 | NULL |
| 23422 | 5 | 1 | NULL |
| 345342 | 6.5 | 6.5 | cat1 |
| 345342 | 6.5 | 2.8 | test |
+-----------+-----------+-----------+------------+

我试着用这样的东西:

SELECT TABLE_A.row_id, TABLE_A.category, TABLE_A.val_1, TABLE_B.val_2
FROM TABLE_A
INNER JOIN TABLE_B ON TABLE_B.row_id = TABLE_A.row_id
ORDER BY row_id;

但是,结果仅包含 TABLE_A 中存在 row_id 列的行。

有没有办法连接 TABLE_A 和 TABLE_B 以产生 RESULT_TABLE 中显示的结果?

最佳答案

尝试外连接。

SELECT TABLE_A.row_id, TABLE_A.category, TABLE_A.val_1, TABLE_B.val_2
FROM TABLE_B
LEFT OUTER JOIN TABLE_A ON TABLE_B.row_id = TABLE_A.row_id
ORDER BY row_id;

关于sql - 如何在 MySQL 中连接具有不同行数的两个表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1792850/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com