首页 文章

基于查找的条件连接

提问于
浏览
1

抱歉如果早些时候发布了类似的问题,我找不到同样的问题 .

问题:我需要在第二个表中基于条件查找连接两个表 .

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

+-------------------------------------------------------+
|                           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字段,并从第二个表条件中获取地址字段:

  • 如果家庭住址的状态可用,则显示家庭住址的街道,城市和州 .

  • 如果家庭住址的状态为空/空白,则显示工作地址的街道,城市和州 .

笔记:

  • Persons表中的许多行没有HomeAddressID,但所有行都有WorkAddressID .

  • 地址表中的许多行没有主页地址的城市和州信息 .

  • 虽然这可能看起来像一个设计缺陷,但我无法重新设计数据库,因为有数百个对象和子对象,具体取决于原始视图 .

  • Persons表中有300万行,因此性能需要接受 .

  • 当前查询已连接至少5个其他视图 .

请告知我如何解决这个问题 .

非常感谢,

-V

2 回答

  • 3

    自联接会处理这个:

    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 将主页更改为左连接

  • 2

    这是一个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
    

相关问题