替代嵌套的select语句

时间:2013-09-24 18:17:06

标签: sql sql-server linq tsql

我有以下表格结构:

enter image description here

目前,过滤用户是通过非常复杂的嵌套SQL查询实现的(而且它是由Linq自动生成的)。我看起来很像:

SELECT FROM (SELECT FROM (SELECT FROM ( infinity here...))))

有简化过滤流程的好方法吗?

请考虑到有不同的特征类型。以下是子查询条件样本:

... WHERE cv.Text like '%aaa%' AND c.Id = 5
... WHERE cv.ImageId IS NOT NULL AND c.Id = 10
... WHERE cv.Number > 5 AND c.Id = 33

等...

将感谢任何帮助和想法(更改数据库结构,更改技术等...),谢谢!

2 个答案:

答案 0 :(得分:1)

正如您所描述的那样,您的查询应该是这样的

select u.id
from Users as u
where
    exists (
        select *
        from CharacteristicValues as cv
        where cv.Text like '%aaa%' and cv.CharacteristicId = 5 and u.Id = cv.UserId
    ) and 
    exists (
        select *
        from CharacteristicValues as cv
        where cv.ImageId is not null and cv.CharacteristicId = 10 and u.Id = cv.UserId
    ) and 
    exists (
        select *
        from CharacteristicValues as cv
        where cv.Number > 5 and cv.CharacteristicId = 33 and u.Id = cv.UserId
    )

甚至

    select distinct cv.UserId
    from CharacteristicValues as cv
    where cv.Text like '%aaa%' and cv.CharacteristicId = 5

    union

    select distinct cv.UserId
    from CharacteristicValues as cv
    where cv.ImageId is not null and cv.CharacteristicId = 10

    union

    select distinct cv.UserId
    from CharacteristicValues as cv
    where cv.Number > 5 and cv.CharacteristicId = 33

答案 1 :(得分:1)

SQL到LINQ将是一个表现不佳的人 如果要优化性能和可伸缩性,请转到TSQL

  1. 数据库设计3nf
  2. 索引
    并且不要过度索引,因为它们会减慢插入并更新
  3. 查询设计
  4. 本地缓存
  5. 本地缓存
    在exe开头下载静态或半静态FK表并将其保存在词典中 然后在你的下拉中使用Dictionary而不是另一个SQL调用 然后在查询中我发送FK ID,以便select少一个连接(它会产生影响)。