簡體   English   中英

從兩個表中選擇不同的結果mysql

[英]Select Distinct results from tow tables mysql

我有兩個表(MYSQL)包含不同的列名,並想查詢表1中的所有數據和表2中不存在的表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;

這種觀點給了我我想要的東西,但是實際上它變慢了,因為我有大數據。 那么還有另一種方法可以得到我的結果嗎?

union all使用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 allunion all並允許您構建索引,但代價是更多的代碼復雜性和空間使用情況。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM