gpt4 book ai didi

mysql - 使用一个查询的结果多次查询另一个表(MySQL)

转载 作者:行者123 更新时间:2023-11-29 06:30:37 25 4
gpt4 key购买 nike

我有两个表,我想得到一个组合了两个表信息的结果。在 table_one 中,我有 4 列:country_code INT(3)、state_code INT(3)、town_code INT(3) 和 class VARCHAR(255)

在 table_two 中,我又有 4 列:country_code INT(3)、state_code INT(3)、town_code INT(3) 和 name VARCHAR(255)。

这两个表无法合并,因为我将来需要向每个表添加列,因为它们有不同的用途。

我正在尝试编写一个 SQL 查询以最终获取以下数据的列表/元组:country_code、state_code、town_code、class、name。我正在寻找一种解决方案,使用 table_one 查询特定州的所有学生,然后搜索这些学生的 3 个识别代码,以在 table_two 中获取每个学生的姓名。我尝试过使用 JOIN 和 UNION 命令,但我似乎还无法让它工作。

Sample Data

table_one
country_code state_code town_code class
001 004 001 9
074 006 003 3
001 003 001 7

table_two
country_code state_code town_code name
001 004 001 John Doe
074 006 003 Jane Doe
001 003 001 First Last

我需要帮助的部分:查询(不是SQL语法):查找居住在country_code = 001的所有学生的country_code、state_code、town_code、类(class)和姓名

Expected Result
country_code state_code town_code class name
001 004 001 9 John Doe
001 003 001 7 First Last

最佳答案

您需要内部联接:

select t1.*, t2.name
from table_one t1 inner join table_two t2
on t2.country_code = t1.country_code and t2.state_code = t1.state_code and t2.town_code = t1.town_code

您可以添加 WHERE 子句来应用您的条件

关于mysql - 使用一个查询的结果多次查询另一个表(MySQL),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56509301/

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