我有两个像这样定义的表。表位置用于存储地址
locations
---------
id
addr
city
zip
name
另一个表引用每个条目的位置表中的两个位置地址存储是
packages
---------
id
client_id
pick_id <-- this id is for the location address for pick
drop_id <-- this id is for the location address for drop
我想要回归
location.name, location.addr, location.city, location.id for pick
location.name, location.addr, location.city, location.id for drop
对于给定的client_id
我目前有这个sql
Select
packages.status,
locations.name,
locations.address,
locations.zip,
locations.city,
locations.id
From
packages Inner Join
locations On packages.drop_id = locations.id And packages.client_id = 5
但是我得到了空行结果。 任何人都可以指出我的错误吗?
答案 0 :(得分:2)
不应该是:
...
ON packages.drop_id = locations.id
WHERE packages.client_id = 5
?
由于JOIN
未使用packages.client_id。
答案 1 :(得分:2)
您似乎只是针对位置表格,而是针对每个放置和选择位置。
要做到这两点,请使用以下内容: -
Select
packages.status,
PickLocation.name,
PickLocation.address,
PickLocation.zip,
PickLocation.city,
PickLocation.id,
DropLocation.name,
DropLocation.address,
DropLocation.zip,
DropLocation.city,
DropLocation.id
From packages
INNER JOIN locations AS PickLocation ON packages.pick_id = PickLocation.id
INNER JOIN locations AS DropLocation ON packages.drop_id = DropLocation.id
WHERE packages.client_id = 5
如果没有返回任何记录,则表明客户端ID 5没有包,或者drop或pick up位置不在位置表上。如果后者尝试使用LEFT OUTER JOIN而不是INNER JOINs