SQL连接具有两种类型的元素的表

时间:2014-01-12 06:07:29

标签: mysql sql database join

我有一个对象表,可以有两种类型:

对象:

id | name | type1 | type2 |
-------------------------
1  | bla  |   5   |   7   |

和类型表

类型:

id | name |
-----------
5  | typ5 |
7  | typ7 |

我如何加入以下内容?

object.id | object.name | typename1 | typename2 |
------------------------------------------------

我尝试了以下操作,但每个对象获得了两行

SELECT objects.id,objetcs.name,types.name
from objects
INNER JOIN types
ON objects.type1=types._id OR objects.type2=types._id

1 个答案:

答案 0 :(得分:2)

您需要两个联接:

SELECT o.id, o.name, t1.name as name1, t2.name as name2
from objects o LEFT OUTER JOIN
     types t1
     ON o.type1 = t1._id LEFT OUTER JOIN
     types t2
     on o.type2 = t2._id;