2015-02-05 96 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

相关问题