好的我对SQL知之甚少,所以请耐心等待......
我正在尝试查看第三级表中是否存在某些值,而我不知道该怎么做。这是场景......
我有一个事故表,可以保存事故信息。它有3个一对多子表(单位,乘员,非摩托车手)。每个子表都有自己的多对多子表(Alcohol)。我需要能够通过某种方式查看这些酒精表中的字段中是否存在一系列值。这是我的表格结构看起来像这样的淡化版本......
--tblAccident--_
PK_AccidentNumber
--tblAccidentUnit--
PK_PrimaryKey
FK_AccidentNumber
--tblAccidentOccupant--
PK_PrimaryKey
FK_AccidentNumber
--tblAccidentNonMotorist--
PK_PrimaryKey
FK_AccidentNumber
--tblAccidentUnitAlcohol--
PK_PrimaryKey
FK_ForeignKey
AlcoholValue <---- THIS IS WHAT I NEED TO SEARCH
--tblAccidentOccupantAlcohol--
PK_PrimaryKey
FK_ForeignKey
AlcoholValue <---- THIS IS WHAT I NEED TO SEARCH
--tblAccidentNonMotoristAlcohol--
PK_PrimaryKey
FK_ForeignKey
AlcoholValue <---- THIS IS WHAT I NEED TO SEARCH
我希望这对我想要完成的事情有所了解。谢谢
答案 0 :(得分:1)
我假设您只想从范围存在的第三级表中获取信息。
尝试下面给出的查询:
由于未指定数据库,因此不确定数据库中的BETWEEN运算符是否包含测试值。
SELECT AccidentNumber, 'AccidentUnit' AS TableFound, c.PrimaryKey AS TableKeyValue
FROM tblAccident a INNER JOIN tblAccidentUnit b
ON a.AccidentNumber = b.AccidentNumber INNER JOIN tblAccidentUnitAlcohol c
ON b.PrimaryKey = c.ForeignKey
AND c.AlcoholValue BETWEEN <RANGE_START> AND <RANGE_END>
UNION
SELECT AccidentNumber, 'AccidentOccupant' AS TableFound, c.PrimaryKey AS TableKeyValue
FROM tblAccident a INNER JOIN tblAccidentOccupant b
ON a.AccidentNumber = b.AccidentNumber INNER JOIN tblAccidentOccupantAlcohol c
ON b.PrimaryKey = c.ForeignKey
AND c.AlcoholValue BETWEEN <RANGE_START> AND <RANGE_END>
UNION
SELECT AccidentNumber, 'AccidentNonMotorist' AS TableFound, c.PrimaryKey AS TableKeyValue
FROM tblAccident a INNER JOIN tblAccidentNonMotorist b
ON a.AccidentNumber = b.AccidentNumber INNER JOIN tblAccidentNonMotoristAlcohol c
ON b.PrimaryKey = c.ForeignKey
AND c.AlcoholValue BETWEEN <RANGE_START> AND <RANGE_END>