SQL查询Where子句问题

时间:2011-03-17 13:27:28

标签: sql

我无法找到查询。

我有一个'NotificationExcludes'表,其中包含1列'Name'。

我有一个表'NotificationEvents',其中包含列:Id,Description。

现在我需要选择所有NotificationEvents,其中描述不以'NotificationExcludes'中包含的值开头。

小例子:

NotificationExcludes包含:

Name
The instance was terminated by

NotificationEvents:

ID  Description
1   There was a failure on ..
2   The instance was terminated by administrator

现在我需要选择所有内容,除非描述以“NotificationExcludes”中保存的值开头。

我试过了

Select Id, Description 
from NotificationEvent 
WHERE Description NOT IN (select Name form NotificationExcludes)

但是有两个问题:

1 The query obviously fails because 'select Name form NotificationExcludes' returns more than 1 record
2 The statement should contain a Like statement where I can use the '%' key. So where description not like 'The instance was terminated by%' can be used somehow

2 个答案:

答案 0 :(得分:4)

SELECT Id,Description
FROM NotificationEvents ne
WHERE NOT EXISTS(SELECT * 
                 FROM NotificationExcludes nx 
                 WHERE ne.Description 
                 LIKE nx.name + '%') /*<--Might need Concat or || here
                                          dependant upon RDBMS*/

答案 1 :(得分:2)

一个解决方案是JOIN名称上带有LIKE子句,附加%

SELECT *
FROM   NotificationEvents ne
       LEFT OUTER JOIN NotificationExcludes nex 
            ON ne.Description LIKE nex.Name + '%' 
WHERE  nex.Name IS NULL