我有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
它只返回带有关联[Product]和[Cost]的[Company],但不返回[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 ║
╚═══════════╩═══════════╩═════════╝
任何帮助将不胜感激。谢谢!
答案 0 :(得分: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