Sql 如何通过联接从两个表中获取值?

Sql 如何通过联接从两个表中获取值?,sql,oracle,select,join,Sql,Oracle,Select,Join,我有两个表表1和表2: 表1: id (primary key) name email category1 (foreign key to table2.id) category2 (foreign key to table2.id) category3 (foreign key to table2.id) 表2:(类别) 我想编写一个select查询来获取类别名称,而不是categoryId 您必须为每个类别加入一次category表(并使用别名来区分它们): 如果table1.catego

我有两个表
表1
表2

表1:

id (primary key)
name
email
category1 (foreign key to table2.id)
category2 (foreign key to table2.id)
category3 (foreign key to table2.id)
表2:(类别)


我想编写一个select查询来获取类别名称,而不是categoryId

您必须为每个类别加入一次category表(并使用别名来区分它们):

如果table1.category*列中的任何一列可以为null,您可能希望使用左联接来确保为其他列返回数据。

令人困惑的问题

假设表2包含CategoryName,而表1包含类别1、2和3的类别id,则可以按以下步骤进行操作:

SELECT t1.id, t2.CategoryName, t3.CategoryName, t4.CategoryName
FROM table1 t1
JOIN table2 t2
ON t1.category1Id = t2.id
JOIN table2 t3
ON t1.category1Id = t3.id
JOIN table2 t4
ON t1.category1Id = t4.id;

同一个表需要3个联接:

SELECT t.id, t.name, t.email, c1.cat_name cn1, c2.cat_name cn2, c3.cat_name cn3 
FROM test t LEFT JOIN cat c1 ON (cat1=c1.id)
            LEFT JOIN cat c2 ON (cat2=c2.id)
            LEFT JOIN cat c3 ON (cat3=c3.id)

使用Mysql进行测试:

能否提供一些表的外观数据?你的开场白有点让人困惑。你从哪里得到CategoryName?我在桌子上也找不到它!表1字段:id、名称、电子邮件、类别1(类别表中的id)…表2字段:id、名称…..我希望查询以获取类别名称而不是id's@TatisettiRamanjaneyulu不要说谢谢,你应该考虑把其中一个答案作为接受。这就是堆栈溢出的最佳工作方式。但是,在表1中,如果cat1、cat2、cat3(ID)中有任何人是空的……我没有得到整行……您能帮忙吗me@TatisettiRamanjaneyulu你必须做一个左边的连接,我会编辑我的答案。“不要说谢谢,你应该考虑把一个答案标记为接受。这就是堆栈溢出的最佳工作方式”。我想接受你的答案。如何做到这一点?@TatisettiRamanjaneyulu:要将答案标记为已接受,请单击答案旁边的复选标记将其从灰色变为已填充。请检查软件,您是最受欢迎的。如果解决方案对您有效,您可以将其标记为答案。谢谢
SELECT t1.id, t2.CategoryName, t3.CategoryName, t4.CategoryName
FROM table1 t1
JOIN table2 t2
ON t1.category1Id = t2.id
JOIN table2 t3
ON t1.category1Id = t3.id
JOIN table2 t4
ON t1.category1Id = t4.id;
SELECT t.id, t.name, t.email, c1.cat_name cn1, c2.cat_name cn2, c3.cat_name cn3 
FROM test t LEFT JOIN cat c1 ON (cat1=c1.id)
            LEFT JOIN cat c2 ON (cat2=c2.id)
            LEFT JOIN cat c3 ON (cat3=c3.id)
SELECT T1.name,
       T1.email,
       C1.name AS CategoryName1,
       C2.name AS CategoryName2,
       C3.name AS CategoryName3
FROM table2 T1 
INNER JOIN table2 C1 
ON T1.category1 = C1.id
INNER JOIN table2 C2 
ON T1.category2 = C2.id
INNER JOIN table2 C3 
ON T1.category3 = C3.id