【问题标题】:Complaints Database Design-SQL Query to show All rows投诉数据库设计-SQL查询显示所有行
【发布时间】:2013-08-14 15:08:57
【问题描述】:

我有一个应用程序,我在其中向已登录的代理显示所有投诉。 我有 100 个代理可以看到相同的投诉屏幕。例如代理 A 和代理 B 登录后可以看到所有的投诉。

> Complaint_id  Complaint_detail
        1            complaint_1    
        2            complaint_2    
        3            complaint_3    

现在的问题是我必须添加功能,让每个代理都可以轻松放置 cmets,或者您可以说一个提醒,例如(agentA put comment:我明天会处理这个评论)。所以这条评论只会显示给agentA。

为了这个实现,我创建了一个新的表,名为commitment_detail,我在其中添加了coloumn 'comment' 和'user_id'

为了显示投诉我写了查询

    select complaint.Complaint_name,complaint.User_ID from complaint 
left outer join complaint_detail on complaint.Complaint_id = complaint_detail.complaint_id

这个查询现在显示所有记录当我过滤用户时它只会显示用户记录来解决这个我添加

    select * from (select complaint.Complaint_name,complaint.User_ID from complaint 
left outer join complaint_detail on complaint.Complaint_id = complaint_detail.complaint_id
complaint_detail.complaint_info_id
) asdf

其中 user_id = 'agentA' 或 User_ID 为空

select * from (
select complaints.complaint_id,complaints.complaint_detail,   complaints_detail.comment,complaints_detail.user_id from complaints
left outer join complaints_detail on complaints.Complaint_id = complaints_detail.complaint_id
) asdf
where user_id = 'agentA'
or User_ID is null

complaint_id    complaint_detail    comment        user_id
         1             complaint_1         complaint_1  agentA
         2             complaint_2         complaint_2  agentA
         3             complaint_3           null            null

为代理B

complaint_id    complaint_detail    comment        user_id
     1             complaint_1          complaint1_ agentB
     3             complaint_3           null            null

任何想法我怎样才能做到这一点,每个用户都可以看到所有的投诉,只有他们的 cmets。我应该更改表结构或查询可以做到这一点吗?

【问题讨论】:

    标签: sql database sql-server-2008 database-design


    【解决方案1】:

    应该这样做:

    select * from complaints cmp
    left outer join comments com on cmp.id=com.complaint_id
    and com.user_id='agentA' or com.user_id is null 
    

    这将从 cmets 表中获取与投诉相关的数据(如果存在)(左连接) 并将 cmets 限制为代理的或没有用户 ID 的评论

    当然,如果您不想从投诉和 cmets 表中检索所有列,您可以在 select 中指定列。

    【讨论】:

    • 实际上这是我的观点,我无法在此查询中传递用户 ID。我必须从我的查询中获取数据并在客户端过滤用户。
    • 所以你只需要所有的投诉 + 带有用户 ID 信息的 cmets 稍后过滤?
    猜你喜欢
    • 2020-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-25
    • 2011-01-29
    • 2011-01-02
    • 1970-01-01
    相关资源
    最近更新 更多