2015-02-05 101 views
1

我有兩個表,我試圖匹配數據,但所有的答案都建議正確的連接或完整連接,這是SQLite上不可用的。匹配來自不同行數的兩個表的數據

Table 1: 

╔═════════╦═════════╦══════╗ 
║ Company ║ Product ║ Cost ║ 
╠═════════╬═════════╬══════╣ 
║ A  ║ abc  ║ 100 ║ 
║ B  ║ abc  ║ 150 ║ 
║ F  ║ xyz  ║ 250 ║ 
║ G  ║ xyz  ║ 300 ║ 
╚═════════╩═════════╩══════╝ 

但是我有更多的公司名單(與同類產品)

Table 2: 

╔═════════╦═════════╗ 
║ Product ║ Company ║ 
╠═════════╬═════════╣ 
║ abc  ║ A  ║ 
║ abc  ║ B  ║ 
║ abc  ║ C  ║ 
║ abc  ║ D  ║ 
║ abc  ║ E  ║ 
║ abc  ║ F  ║ 
║ abc  ║ G  ║ 
║ xyz  ║ A  ║ 
║ xyz  ║ B  ║ 
║ xyz  ║ C  ║ 
║ xyz  ║ D  ║ 
║ xyz  ║ E  ║ 
║ xyz  ║ F  ║ 
║ xyz  ║ G  ║ 
╚═════════╩═════════╝ 

如何匹配,以便他們這個樣子?

Table 3: 

╔═════════╦═════════╦══════╗ 
║ Product ║ Company ║ Cost ║ 
╠═════════╬═════════╬══════╣ 
║ abc  ║ A  ║ 100 ║ 
║ abc  ║ B  ║ 150 ║ 
║ abc  ║ C  ║ null ║ 
║ abc  ║ D  ║ null ║ 
║ abc  ║ E  ║ null ║ 
║ abc  ║ F  ║ null ║ 
║ abc  ║ G  ║ null ║ 
║ xyz  ║ A  ║ null ║ 
║ xyz  ║ B  ║ null ║ 
║ xyz  ║ C  ║ null ║ 
║ xyz  ║ D  ║ null ║ 
║ xyz  ║ E  ║ null ║ 
║ xyz  ║ F  ║ 250 ║ 
║ xyz  ║ G  ║ 300 ║ 
╚═════════╩═════════╩══════╝ 

當我使用此代碼,

SELECT Company, t.Product, Cost 
FROM table1 as t INNER JOIN table2 as f ON t.product = f.product 
WHERE t.company = f.company 

它只返回[公司]與相關的[產品]和[費用],但不與空值返回[公司]。

當我使用

SELECT Company, t.Product, Cost 
FROM table1 as t INNER JOIN table2 as f ON t.company = f.company 

那麼我的輸出看起來像

╔═══════════╦═══════════╦═════════╗ 
║ t.Company ║ f.Company ║ Product ║ 
╠═══════════╬═══════════╬═════════╣ 
║ A   ║ A   ║ abc  ║ 
║ B   ║ A   ║ abc  ║ 
║ F   ║ A   ║ abc  ║ 
║ G   ║ A   ║ abc  ║ 
║ A   ║ B   ║ abc  ║ 
║ B   ║ B   ║ abc  ║ 
║ F   ║ B   ║ abc  ║ 
║ G   ║ B   ║ abc  ║ 
║ A   ║ C   ║ abc  ║ 
║ B   ║ C   ║ abc  ║ 
║ F   ║ C   ║ abc  ║ 
║ G   ║ C   ║ abc  ║ 
╚═══════════╩═══════════╩═════════╝ 

任何幫助將非常感激。謝謝!

回答

1

的SQLite 確實支持LEFT OUTER JOIN,它應該做的工作就好了:

select two.product, two.company, one.cost from two 
left outer join one on 
    ((one.company = two.company) and (one.product = two.product)); 

(其中two是你的 「表2」 和one是你的 「表1」)

運行此在上述數據的SQLite:

abc|A|100 
abc|B|150 
abc|C| 
abc|D| 
abc|E| 
abc|F| 
abc|G| 
xyz|A| 
xyz|B| 
xyz|C| 
xyz|D| 
xyz|E| 
xyz|F|250 
xyz|G|300 
+0

我甚至不認爲我可以加入多個列(即,(( one.company = two.company)和(one.product = two.product));)。總新手錯誤!非常感謝您的幫助! – vanellope1 2015-02-06 00:01:56

相關問題