【问题标题】:How to add extra value to select query result如何添加额外的值来选择查询结果
【发布时间】:2020-02-21 11:43:05
【问题描述】:

学科硕士

Id  Subject
1   English
2   History
3   Maths

用户主题关联

Id Userid SubjectId
1   1     1
2   1     3
3   2     2

日志

Id  Userid  SubjectId Examdate     Percentage 
1   1       1          02/20/2020  50
2   1       0          Null        Null
3   2       1           02/20/2020  70
4   2       2           02/20/2020  60
5   3       0            Null        Null
6   4       3           02/18/2020  56

这些是我的示例表。

我想显示来自零日志表的记录以及用户 1 的所有分配主题

假设用户 1 有 2 个主题 1 和 3。 显示日志中 subjectid 为 0 和 1,3 的记录

所需输出:

日志

Id  Userid  SubjectId Examdate     Percentage 
1   1       1          02/20/2020  50
2   1       0          Null        Null
3   2       1           02/20/2020  70
4   3       0            Null        Null
5  4       3           02/18/2020  56

查询:

select * from logs where rdatetime >= '' and subjectid in (select id from subjectmaster where userid = 1)

“或”不起作用。它给出了错误的输出。如何处理它。

【问题讨论】:

  • 用您正在使用的数据库标记您的问题。
  • 我正在使用 sql server 2013。我已经显示了所需的输出

标签: sql asp.net sql-server


【解决方案1】:

如果我理解正确,您需要这样的相关子查询和条件:

select l.*
from logs l 
where l.subjectid = 0 or
      exists (select 1
              from subjectmaster sm
              where sm.userid = l.userid and
                    sm.subjectid = l.subjectid
             );

【讨论】:

    【解决方案2】:

    你可以left join

    select l.*
    from logs l left join
         subjectmaster sm
         on sm.userid = l.userid and
            sm.subjectid = l.subjectid
    where not (l.subjectid <> 0 and sm.subjectid is null);
    

    【讨论】:

      【解决方案3】:

      这个查询会给你想要的结果:

      select * 
      from logs l
      where subjectid = 0 
            OR
            subjectid IN (select subjectid 
                          from UserSubjectAssociation 
                          where Userid = 1)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-12-18
        • 1970-01-01
        • 2013-12-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多