【问题标题】:SQL Query, how to get all elements from one list and only the similar ones from another tableSQL Query,如何从一个列表中获取所有元素,而仅从另一表中获取相似的元素
【发布时间】:2016-11-09 03:45:03
【问题描述】:

我有 2 个表,它们具有 PartID 作为它们的相似性来分支它们。我需要从第一个表中提取 3 列,从表 2 中提取 2 列。

我遇到的问题是表 1 有时比表 2 具有更多或不同的 PartID,这没关系。在第三个表中,我希望能够有一个可以运行的查询,并为我提供第一个表和第二个表中的所有 PartID,即使它们不存在于另一个表中。但是,如果它们都存在于两者中,我希望数据像往常一样放在一起

此代码显示两个表之间相似的 PartID:

SELECT `Sheet1$`.ENSPIECEID, `Sheet1$`.`Part Number`, `Sheet1$`.Description,`Sheet1$`.TITRETYPE, `Sheet1$`.Utilization, `Sheet2$`.Notes, `Sheet2$`.Justification
FROM `Sheet1$` `Sheet1$`, `Sheet2$` `Sheet2$`
WHERE `Sheet1$`.ENSPIECEID = `Sheet2$`.ENSPIECEID

我需要这个,以便我可以标记哪些 PartID 仅来自第一张工作表,哪些仅来自第二张工作表。

【问题讨论】:

    标签: mysql sql excel join


    【解决方案1】:

    你可以这样做(你必须用你的表名和列名替换):

    对于这个例子,我使用了测试表结构:See it here

    tab1 (partid int, description varchar(100))
    tab2 (partid int, variation varchar(100))
    

    在两个表中选择零件 ID

    select *
    from tab1 t1
    join tab2 t2 on t1.partid = t2.partid;
    

    选择仅在第一个表中的零件 ID

    select * 
    from tab1 t1
    left outer join tab2 t2 on t1.partid = t2.partid
    where variation is null;
    

    选择仅在第二个表中的零件 ID

    select * 
    from tab2 t2
    left outer join tab1 t1 on t2.partid = t1.partid
    where description is null;
    

    所以要选择不在另一个表中的所有零件ID,请合并最后两个查询的结果

    select t1.partid 
    from tab1 t1
    left outer join tab2 t2 on t1.partid = t2.partid
    where variation is null
    union
    select t2.partid 
    from tab2 t2
    left outer join tab1 t1 on t2.partid = t1.partid
    where description is null;
    

    【讨论】:

    • 更彻底的回应
    【解决方案2】:
    SELECT `Sheet1$`.ENSPIECEID, `Sheet1$`.`Part Number`, `Sheet1$`.Description,`Sheet1$`.TITRETYPE, `Sheet1$`.Utilization, `Sheet2$`.Notes, `Sheet2$`.Justification
    FROM `Sheet1$` `Sheet1$`
    LEFT JOIN `Sheet2$` `Sheet2$` on `Sheet1$`.ENSPIECEID = `Sheet2$`.ENSPIECEID
    

    将返回工作表 1 中的所有记录,并且只返回工作表 2 中匹配的记录;假设没有其他语法错误。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-21
      • 2016-01-14
      相关资源
      最近更新 更多