使用具有相同外键的两列

时间:2011-03-15 10:53:37

标签: mysql sql phpmyadmin

我有一个数据库,有5个表,但我有问题。在货件表中,有两列,source和destination,它们都是路由表的外键引用,但是当我从货件表中选择一条记录时,它只会为两者显示相同的路由名。

以下是代码:

SELECT fare, commission, driver,shipment._date, routename, vehiclenumber, productname, source, destination, routename,ownername
FROM route, shipment, product, vehicle,owner
WHERE vehicle.vehicleid = shipment.vehicle
AND shipment.source
and vehicle.owner=owner.ownerid
AND shipment.destination = route.routeid
AND shipment.product = product.productid
AND vehicle.vehiclenumber =  'nk-234'
ORDER BY _date
LIMIT 0 , 30

3 个答案:

答案 0 :(得分:3)

要将一个表(一个货件)中的记录连接到另一个表中的多个记录(两个路径),理想情况下,对JOIN表的显式route使用两次(或更多,因为你碰巧需要很多链接。)

以下是对您的查询的快速修改,以演示用法。请特别注意routename中的两个SELECT列和JOINroute表中的两个FROM

SELECT fare,
       commission,
       driver,
       shipment._date,
       RS.routename,    <-- field from first join
       vehiclenumber,
       productname,
       source,
       destination,
       RD.routename,    <-- field from second join
       ownername

FROM shipment
JOIN route RS ON RS.routeID = shipment.source       <-- join 1; source
JOIN route RD ON RD.routeID = shipment.destination, <-- join 2; destination
     product,
     vehicle,
     owner

WHERE vehicle.vehicleid = shipment.vehicle
  AND vehicle.owner = owner.ownerid
  AND shipment.product = product.productid
  AND vehicle.vehiclenumber =  'nk-234'

ORDER BY _date

LIMIT 0 , 30

显然,这可能不完全符合您的需求,因为我不知道其他所选字段来自哪些表格,以确保它们全部被占用...

答案 1 :(得分:1)

这是因为您从出货中的一行中选择了字段,以便实际从外键获得任何效果,您需要使用一些连接

http://dev.mysql.com/doc/refman/5.5/en/join.html

答案 2 :(得分:1)

使用旧式(非首选)表示法,您可以写:

SELECT s.fare, s.commission, s.driver, s._date, v.vehiclenumber, p.productname,
       s.source, s.destination, rs.routename, rd.routename, o.ownername
  FROM route AS rs, route AS rd, shipment AS s, product AS p, vehicle AS v, owner AS o
 WHERE s.vehicleid = s.vehicle
   AND s.source = rs.routeid
   AND v.owner = o.ownerid
   AND s.destination = rd.routeid
   AND s.product = p.productid
   AND v.vehiclenumber =  'nk-234'
 ORDER BY _date
 LIMIT 0, 30

我不得不猜测哪个表包含票价,佣金和司机信息;我以为他们都在装运表中。

在标准SQL中,严格不允许使用下划线启动列名,尽管大多数DBMS都允许。但它看起来很丑陋;为什么不将'ship_date'作为列名?

最好使用显式连接表示法,尤其是因为忘记连接条件的可能性较小:

SELECT s.fare, s.commission, s.driver, s._date, v.vehiclenumber, p.productname,
       s.source, s.destination, rs.routename, rd.routename, o.ownername
  FROM shipment AS s
  JOIN route    AS rs ON s.source      = rs.routeid
  JOIN route    AS rd ON s.destination = rs.routeid
  JOIN vehicle  AS v  ON s.vehicleid   = s.vehicle
  JOIN owner    AS o  ON v.owner       = o.ownerid
  JOIN product  AS p  ON s.product     = p.productid
 WHERE v.vehiclenumber = 'nk-234'
 ORDER BY s._date
 LIMIT 0, 30