如何从外键表访问数据

时间:2014-12-30 09:34:26

标签: mysql sql database select join

我有三张表公司,用户,地址。

 公司有三个字段

  • comp_id(PK)
  • COMP_NAME
  • USER_ID(FK)
  • to_address_id(FK)
  • from_address_id(FK)

    地址包含字段:

  • ADDRESS_ID(PK)
  • 城市
  • 状态

    用户有字段 USER_ID(PK),USER_NAME

    to_address_id和from_address_id都是外键,它引用相同的表地址并映射到address_id

    现在重点是如何从表中检索from_address,我能够从此查询中检索to_address。

    在这里,我可以从Shipment表中获取to_address_id和from_address_id,但是如何根据address_id获取同一查询中的两个地址:

 SELECT s.comp_name,u.user_name,a.city
            FROM
        company s
    JOIN
        User u
    JOIN
        Address a
    ON
        s.user_id = u.user_id 
        AND s.to_address_id = a.address_id
    WHERE
        s.user_id = 1001;

3 个答案:

答案 0 :(得分:2)

解决方案 - 您需要加入两次,每次对于您感兴趣的每个FK:

SELECT s.comp_name, u.user_name, a_from.city AS city_from, a_to.city AS city_to
FROM company s
LEFT JOIN User u ON s.user_id = u.user_id 
LEFT JOIN Address a_from ON s.from_address_id = a_from.address_id
LEFT JOIN Address a_to ON s.to_address_id = a_to.address_id
WHERE s.user_id = 1001;

答案 1 :(得分:1)

尝试以下方法:

 SELECT s.comp_name
        ,u.user_name
        ,a1.city
        ,a2.city 
 FROM company s 
 JOIN User u ON s.user_id = u.user_id  
 JOIN Address a1 ON s.to_address_id = a1.address_id 
 JOIN Address a2 ON s.from_address_id = a2.address_id
 WHERE s.user_id = 1001;

答案 2 :(得分:0)

您必须先查看在查询中使用 JOIN

试试这个:

SELECT s.comp_name,u.user_name,a.city
FROM company s
JOIN User u ON s.user_id = u.user_id 
JOIN Address a ON s.to_address_id = a.address_id
WHERE s.user_id = 1001;