如何改进此SQL查询?

时间:2015-01-26 14:46:19

标签: sql sqlite

自从我使用SQL以来已经有一段时间了,我不记得从链接表中获取数据的最佳方法。从表格Cat和Bat获取数据的最佳方法是什么?

Apple
---------
batId
catId

Bat
---------
id
batField1
batField2
batField3

Cat
---------
id
catField1
catField2
catField3

我正在尝试获取batField1,batField3和catField1。 这是我当前的查询

SELECT b.batField1, b.batField3, c.catField1
FROM Apple AS a, Bat as b, Cat as c
WHERE a.batId = b.id OR a.catId = c.id;

2 个答案:

答案 0 :(得分:2)

SELECT b.batField1, b.batField3, c.catField1
FROM Apple AS a
LEFT JOIN Bat as b ON A.BatID = b.ID
LEFT JOIN Cat as c ON A.CatID = c.ID

答案 1 :(得分:1)

SELECT b.batField1, b.batField3, c.catField1
FROM Bat b
INNER JOIN Apple a ON b.Id = a.batID
INNER JOIN Cat c ON a.catId = c.id