0

我有两个这样定义的表。表位置用于存储地址

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

但我得到空行的结果。谁能指出我的错误?

4

2 回答 2

2

不应该是:

...
ON packages.drop_id = locations.id
WHERE packages.client_id = 5

? 由于 packages.client_id 不被JOIN.

于 2013-06-26T12:54:08.517 回答
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 没有包裹,或者放置或提取位置不在位置表上。如果是后者,请尝试使用 LEFT OUTER JOINs 而不是 INNER JOINs

于 2013-06-26T12:57:57.710 回答