我有2个表,我试图对数据进行匹配,但是所有答案都建议使用正确的联接或完全联接,这在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     ║
╚═══════════╩═══════════╩═════════╝


任何帮助都感激不尽。谢谢!

最佳答案

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

10-01 23:44
查看更多