【问题标题】:How to get values from two tables by joins?如何通过连接从两个表中获取值?
【发布时间】:2015-05-11 10:28:24
【问题描述】:

我有两张桌子table1table2

table1:

id (primary key)
name
email
category1 (foreign key to table2.id)
category2 (foreign key to table2.id)
category3 (foreign key to table2.id)

table2:(类别)

id (primary key)
name

我想编写一个选择查询来获取类别名称而不是 categoryId。

【问题讨论】:

  • 您能否提供一些有关您的表格的数据?您的开场问题有点令人困惑。
  • 您从哪里获得 CategoryName?我在table2中也找不到!
  • table1 字段:id、name、email、category1(类别表中的id)......
  • table2 字段 : id , name.....
  • 我想要一个查询来获取包含 id 的类别名称

标签: sql oracle select join


【解决方案1】:

同一张表需要 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测试:DEMO

【讨论】:

  • 但是,如果在 table1 中 cat1,cat2,cat3(ids) 任何人都是空的.......我没有得到整行......你能帮我吗
  • @TatisettiRamanjaneyulu 您必须进行左连接,请编辑我的答案。
  • @TatisettiRamanjaneyulu 对此感到高兴:) 请考虑选择答案
  • 一些人评论了我的评论“与其说谢谢,不如考虑将其中一个答案标记为已接受。这就是 Stack Overflow 的最佳工作方式”。我想接受你的回答。该怎么做?
  • @TatisettiRamanjaneyulu :要将答案标记为已接受,请单击答案旁边的复选标记以将其从灰色切换为已填充,请检查 SOF help
【解决方案2】:

令人困惑的问题..

假设表 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 
    t1.id, 
    t1.name, 
    t1.email, 
    t2_cat1.name,
    t2_cat2.name,
    t2_cat3.name
from 
    table1 t1 
join 
    table2 as t2_cat1 on t1.category1 = t2_cat1.id
join 
    table2 as t2_cat2 on t1.category2 = t2_cat2.id
join 
    table2 as t2_cat3 on t1.category3 = t2_cat3.id

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

【讨论】:

  • @TatisettiRamanjaneyulu 与其说谢谢,不如考虑将其中一个答案标记为已接受。这就是 Stack Overflow 的最佳工作方式。
【解决方案4】:
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

【讨论】:

    猜你喜欢
    • 2018-08-17
    • 1970-01-01
    • 1970-01-01
    • 2019-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多