SQL在通用表的不同表中查找值

时间:2015-12-10 19:15:21

标签: sql sql-server sql-server-2008

我有3张桌子

| Id | Name  |
|----|-------|
|   1|   Cat1|
|   2|   Cat2|
|   3|   Cat3|

| Id | Name  |
|----|-------|
|  1 |   Dog1|
|  2 |   Dog2|
|  3 |   Dog3|

所有者

| Id | Name  |TableName |EntityId|
|----|-------|--------------------
|  1 |   John|   Dog    |       1|
|  2 |   Pete|   Cat    |       1|
|  3 |Jessica|   Cat    |       2|

我无法控制动物表,我的意思是,可能是N动物表,猫和狗只是一个例子。

有一种方法可以在一个选择查询中获取猫和狗的名字吗? 结果必须是

| OwnerId | Name  |TableName |EntityId|AnimalName|
|---------|-------|-------------------------------
|  1      |   John|   Dog    |       1|     Dog1 |
|  2      |   Pete|   Cat    |       1|     Cat1 |
|  3      |Jessica|   Cat    |       2|     Cat2 |

3 个答案:

答案 0 :(得分:1)

您可以使用case语句:

select o.id, o.name, 
    case when o.tablename = 'dogs' then d.name else c.name end name
from owner o 
    left join cats c on o.entityid = c.id and o.tablename = 'cats'
    left join dogs d on o.entityid = d.id and o.tablename = 'dogs'

正如其他人所提到的,如果您有机会更新数据模型,那么这可能会轻松得多。有一个Pet表,一个Owner表和一个OwnerPet表(x-ref表)。然后它是inner join的简单查询。

答案 1 :(得分:0)

如果我是你,我会将你的表架构修改为:

  • PetType

    • PetTypeId
    • PetTypeName
  • 宠物

    • PetId
    • PetTypeId
    • PetName
  • 所有者

    • OWNERID
    • OWNERNAME
  • OwnerPet

    • OWNERID
    • PetId

然后你可以这样做:

select *
from Owner
join OwnerPet on OwnerPet.OwnerId = Owner.OwnerId
join Pet on OwnerPet.PetId = Pet.PetId
join PetType on Pet.PetTypeId = PetType.PetTypeId

SQL Fiddle Example

答案 2 :(得分:0)

您可以使用左连接或联合来完成此任务,两种方法都在下面提到

SELECT 
    OW.ID,OW.Name,OW.TableName,OW.EntityId,
    CASE WHEN OW.TableName='Cat' THEN CA.Name ELSE DO.Name END AnimalName
FROM Owner OW
LEFT JOIN Cats CA ON OW.EntityId=CA.ID AND OW.TableName='Cat'
LEFT JOIN Dogs DO ON OW.EntityId=DO.ID AND OW.TableName='Dog'

SELECT 
    OW.ID,OW.Name,OW.TableName,OW.EntityId,CA.Name AnimalName
FROM Owner OW
JOIN Cats CA ON OW.EntityId=CA.ID AND OW.TableName='Cat'
UNION
SELECT 
    OW.ID,OW.Name,OW.TableName,OW.EntityId,DO.Name AnimalName
FROM Owner OW
JOIN Dogs DO ON OW.EntityId=DO.ID AND OW.TableName='Dog'