三行加入mysql两次成功第三次没有

时间:2013-05-08 21:30:45

标签: mysql sql join

我有三个表人物,物品和地点。人们只能拥有1件物品。地点与2个表中的任何一个都没有关系。我想让我记录加入所有3.我做了2到目前为止人们+项目但是第3次我不断收到MySQL错误。位置没有JOIN ON。有帮助吗?

SELECT * FROM ITEMS i 
RIGHT JOIN PEOPLE p 
ON (p.ITEM_ID =i.ID) where
 p.ID=3 

RIGHT JOIN 

SELECT * FROM LOCATIONS lo where lo.ID=7

3 个答案:

答案 0 :(得分:0)

尝试这样的事情:

SELECT peo.id, it.id, loc.id
FROM People as peo
INNER JOIN Items as it on it.id = peo.id
INNER JOIN Locations as loc on loc.id = peo.id
WHERE peo.ID=3 

编辑: 我在输入时编辑了您的问题所以我的示例与以前不匹配。根据需要使用ITEM_ID和ID。

虽然不推荐,但您也可以使用

SELECT *
FROM People as peo
INNER JOIN Items as it on it.id = peo.id
INNER JOIN Locations as loc on loc.id = peo.id
WHERE peo.ID=3 

答案 1 :(得分:0)

如果没有共同的join个密钥,那么您可能需要执行cross join。这会生成笛卡尔积,即从People / items中选择的每一行的每个位置:

SELECT * 
FROM ITEMS i RIGHT JOIN 
     PEOPLE p 
     ON (p.ITEM_ID =i.ID) cross join
     location l
WHERE p.ID=3

顺便说一句,MySQL有一个非常灵活(和非标准)join的语法。您实际上可以将on子句从join中删除,它的行为与cross join相同。当然,这是一个坏习惯。如果您想要交叉联接,请明确使用cross join

答案 2 :(得分:0)

我假设您希望每行显示ID为7的位置...

SELECT * 
    ,(SELECT loc.name FROM Location loc WHERE loc.ID = 7) AS Location
FROM ITEMS i 
RIGHT JOIN PEOPLE p 
ON (p.ITEM_ID =i.ID)
WHERE p.ID=3 

OR

SELECT * 
FROM ITEMS i 
RIGHT JOIN PEOPLE p 
ON (p.ITEM_ID =i.ID)
CROSS JOIN (SELECT * FROM LOCATIONS lo where lo.ID=7) l 
WHERE p.ID=3 

OR

[several other ways to go about it]