我需要在 SQL Server 数据库上创建一个视图,其中一个列可能来自两个源中的任何一个,具体取决于存在的内容。具体来说,我们有一系列这样的表(简化):
表 1:
personid
typeid (one of the values from Table2)
surname
forename
etc...
表2:
typeid
typename
etc...
表 3:
attributeid
attributename
etc...
表 4:
valueid
attributeid (one of the values from table3)
typeid (one of the values from table2)
personid (one of the values from table1)
attributevalue
etc...
现在,我需要(除其他外)从 table4 中选择适用于一个人的“属性值”的值。这可能看起来很简单(加入 personid 就完成了),但并不是那么简单。表 4 中可能没有 personid 的行,在这种情况下,我们需要默认为与类型关联的属性值。换句话说,从逻辑上讲,它是
if (there exists an attributevalue in t4 associated with personid)
use it
else
use attributevalue in t4 associated with typeid
我希望这很清楚。我一直在尝试确定是否可以通过一些微妙的连接或合并来完成,但一直无法弄清楚。
不幸的是,我对 SQL 的练习并不多,因此非常感谢一些指针!
最终,我希望不能使用 t3 中的属性名来编写查询(因此在此处包括它),但现在的症结在于为每个属性获取正确的值。
提前致谢
编辑:根据以下建议进行更新(评论太长!):
感谢您的输入。我已经尝试过了,但它并没有返回我们所期望的。以下是数据示例:
表格1:
PersonID 184
TypeID 49
...etc...
表 4:
valueid 423 424 425 426 431 432
attributeid 4 5 6 7 6 5
typeid 49 49 49 49 49 49
personid NULL NULL NULL NULL 184 184
attributevalue yes track no no yes pay
etc...
所以我们期望的人 id 184 的属性值是
4: yes
5: pay
6: yes
7: no
(默认为与相关 typeid 关联的值,其中没有与非空 personid 关联的值)
为了清楚起见,稍微修改查询:
SELECT distinct t.id, p.AttributeID, isnull(p.attributevalue, p1.attributevalue) AS attributevalue
FROM table1 as T
LEFT JOIN table4 AS p ON p.personID = t.personID
left JOIN table4 p1 ON p1.typeID = t.typeID
where t.ID=184
我们回来
id AttributeID attributevalue
184 5 pay
184 6 yes
因此,它正确地撤回了存在特定于 personid 的覆盖的值,而不是默认值。
任何更多的想法将不胜感激!
再次感谢
第二次更新:
感谢这里的建议。最后,我选择了其他地方的一个,即使用一个函数并在我需要插入一个值的每个地方调用它。它只是为给定的人/类型/属性组合返回适当的值。奇迹般有效。