基于查找的条件连接

时间:2014-04-10 22:48:37

标签: sql conditional left-join lookup

如果早先发布了类似的问题,我很抱歉,我找不到同样的问题。

问题:我需要在第二个表中根据条件查找连接两个表。

表:下面是两个包含总字段子集的表。

+-------------------------------------------------------+
|                           Persons                     |
+----------+------------+---------------+---------------+
| PersonID | PersonName | HomeAddressID | WorkAddressID |
+----------+------------+---------------+---------------+
| P1       | Doe, John  | HA1           | WA1           |
+----------+------------+---------------+---------------+
| P2       | Doe, Jane  | HA2           | WA2           |
+----------+------------+---------------+---------------+
| P3       | Doe, Jane  |               | WA3           |
+----------+------------+---------------+---------------+


+-----------------------------------+
|             Addresses             |
+-----------+--------+------+-------+
| AddressID | Street | City | State |
+-----------+--------+------+-------+
| HA1       | 123    | A    | B     |
+-----------+--------+------+-------+
| WA1       | 456    | C    | D     |
+-----------+--------+------+-------+
| HA2       | 111    |      |       |
+-----------+--------+------+-------+
| WA2       | 101    | G    | H     |
+-----------+--------+------+-------+
| WA3       | 333    | I    | J     |
+-----------+--------+------+-------+

当前场景:视图中的SELECT查询从第一个表中获取PersonName,从第二个表中获取工作地址字段。 (加入WorkAddressID)

预期结果:SELECT查询应从第一个表中获取PersonName字段,并从第二个表条件中获取地址字段:

  1. 如果家庭住址的状态可用,则显示街道,城市和州的家庭住址。
  2. 如果家庭住址的状态为空/空白,则显示工作地址的街道,城市和州。
  3. 注意:

    1. Persons表中的许多行没有HomeAddressID,但所有行都有WorkAddressID。
    2. 地址表中的许多行没有家庭住址的城市和州信息。
    3. 虽然这可能看起来像设计缺陷,但我无法重新设计数据库,因为有数百个对象和子对象,具体取决于原始视图。
    4. Persons表中有300万行,因此性能需要接受。
    5. 当前查询已连接至少5个其他视图。
    6. 请告知我如何解决这个问题。

      非常感谢,

      -V

2 个答案:

答案 0 :(得分:3)

这是一个MySQL解决方案:

SELECT PersonName, 
       IF(h.State = '' OR h.State IS NULL, w.Street, h.Street) AS Street,
       IF(h.State = '' OR h.State IS NULL, w.City, h.City) AS City,
       IF(h.State = '' OR h.State IS NULL, w.State, h.State) AS State
FROM Persons AS p
JOIN Addresses AS w ON w.AddressID = p.WorkAddressID
LEFT JOIN Addresses as h ON h.AddressID = p.HomeAddressID

答案 1 :(得分:2)

自我加入可以解决这个问题:

select
    p.personname,
    case when ha.state is null then wa.street else ha.street end as street,
    case when ha.state is null then wa.city else ha.city end as city,
    case when ha.state is null then wa.state else ha.state end as state
from
    Persons p
    inner join addresses wa on p.workaddressid = wa.addressid
    left join addresses ha on p.homeaddressid = ha.addressid

此语法适用于MSSQL

修改:由于标准Many rows in Persons table do not have HomeAddressID

,将主页更改为左连接