1

假设我有一个包含以下记录的表

value                    text
company/about            about Us
company                  company
company/contactus        company contact

我在 sql server 中有一个非常简单的查询,如下所示。我对“或”条件有疑问。在下面的查询中,我正在尝试查找值“公司/关于”的文本。如果没有找到,那么只有我想运行'或'的另一面。以下查询返回两条记录,如下所示

value                       text
company/about               about Us
company                     company

询问

 select 
        *
    from 
        tbl
    where 
        value='company/about' or
         value=substring('company/about',0,charindex('/','company/about'))

如何修改查询,使结果集看起来像

value                       text
company/about               about Us
4

2 回答 2

1

有点迂回,但您可以检查第一个 where 子句的结果是否存在:

select 
    *
from 
    tbl
where 
    value='company/about' or
(
    not exists (select * from tbl where value='company/about')
    and
    value=substring('company/about',0,charindex('/','company/about'))
)
于 2012-10-04T21:26:31.787 回答
1

由于您的第二个条件可以重写,因为value = 'company'这会起作用(至少对于您提供的数据和查询):

select top(1) [value], [text]
from dbo.MyTable
where value in ('company/about', 'company')
order by len(value) desc

The TOP() ignores the second row if both are found, and the ORDER BY ensures that the first row is always the one with 'company/about', if it exists.

于 2012-10-04T21:35:17.963 回答