【问题标题】:Select Distinct results from tow tables mysql从两个表mysql中选择不同的结果
【发布时间】:2015-07-11 09:31:31
【问题描述】:

我有两个表(MYSQL)包含不同的列名,我想查询表 1 中的所有数据以及表 2 中不存在于表 1 中的所有数据

数据如下: 表一

Ref     Desc    Price

A       TEXT1     12
B       TEXT2     10
C       TEXT3     5

表 2:

Code     Desc    Price

A       TEXT1     7
B       TEXT2     10
D       TEXT4     2

我希望结果是这样的:

Ref     Desc    Price

A       TEXT1     12
B       TEXT2     10
C       TEXT3     5
D       TEXT4     2

所以我试图做出这样的看法:

CREATE  OR REPLACE VIEW `partsquery` AS
SELECT  table1.Ref AS reference,    
        table1.Desc AS description,
        table1.Price AS price
        FROM table1
UNION ALL
SELECT  t2.code AS Ref,
        t2.Desc AS description,
        t2.price  AS price
FROM
    table2 AS t2
    LEFT JOIN table1 AS t1
    ON 
            t2.Code = t1.Ref
WHERE t1.Ref Is Null;

这个视图给了我我想要的,但实际上它很慢,因为我有大数据。那么还有其他方法可以得到我的结果吗?!

【问题讨论】:

    标签: mysql sql join views


    【解决方案1】:

    使用union all:

    select t1.*
    from table1 t1
    union all
    select t2.*
    from table2 t2
    where not exists (select 1 from table1 t1 where t1.code = t2.code);
    

    为了性能,您需要在table1(code) 上的索引。

    我想不出更快的方法来运行这个查询。

    如果您快速需要这些数据,您可能需要创建第二个表,以及前两个表的触发器。触发器将根据您的条件插入新行。这将摆脱 union all 并允许您构建索引,但代价是更多的代码复杂性和空间使用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-28
      • 2016-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多