我正在努力处理需要加入数据的查询。 我有一张包含各种状态信息的表格。它们有一个failureBitNr,例如“a1_1”。然后我有第二个表将“a1_1”翻译成人类可读的文本(lng_English)。默认情况下,第二个表具有“a1_1”的翻译。但是这也可以被另一个特定的翻译覆盖,例如当failureBitNr用于另一个状态而不是标准时。
所以我需要将状态表与failureBitNr上的转换表一起加入。那并不难。
但是如何加入覆盖基本翻译的翻译呢?
表2如下所示:
id fileProjectNr MachineNr failureBitNr lng_English
905 2203456 2 a6_1 This message overwrites the standard
205 NULL NULL a6_1 Standard message for a6_1
204 NULL NULL a1_1 Standard message for A1_1
203 NULL NULL a1_2 Standard message for A1_2
注意覆盖现有消息的消息包含一个非NULL的fileProjectNr。所有标准消息都有一个fileProjectNr NULL
因此仅在FailureBitNr上加入将返回两行(905和205)。但我需要加入failureBitNr并做一些不是fileProjectNr的NULL。
所以我这样做了:
DECLARE @ProjectNr int = 123456
SELECT
t1.*,
t2.*
FROM
Table1 AS t1
LEFT JOIN
Table2 AS t2
ON
(t1.failureBitNr = t2.failureBitNr)
AND
(t2.fileProjectNr LIKE
CASE WHEN t2.fileProjectNr = @ProjectNr THEN
@ProjectNr
ELSE
NULL
END
)
WHERE
{where statement}
这将返回ID 905,但是如果在failureBitNr a1_1和a1_2上也有连接,则这些将全部返回为“NULL”而不是“ax_x的标准消息”。
有人想知道如何解决这个问题吗?
答案 0 :(得分:2)
我的第一个想法:
SELECT t1.*, t2.* FROM Table1 AS t1
LEFT JOIN Table2 AS t2 (t1.failureBitNr = t2.failureBitNr)
where t2.fileProjectNr is not NULL
union all
SELECT t1.*, t2.* FROM Table1 AS t1
LEFT JOIN Table2 AS t2 (t1.failureBitNr = t2.failureBitNr) and
where t1.failureBitNr not in (select failureBitNr from Table2 where fileProjectNr is not NULL)
答案 1 :(得分:1)
取代加入,使用UNION ALL
,然后使用GROUP BY
failureBitNr
和SELECT
lng_English
MAX(fileProjectNr)
或MAX
fileProjectNr