如何从条件表中检索数据?

时间:2019-05-16 12:59:59

标签: mysql sql

我正在开发到mysql服务器中的数据库视图,通过将grns加入注释表来获取grns的状态。我想显示grn被拒绝或批准。评论表上的单个grns可能有几个评论。

如果grn的注释表状态中的grn仅有一个“批准”,则必须返回为“已批准”,否则将返回“已拒绝”或“待处理”。这是两个表的虚拟对象。

grn and comment tables

预期结果:

G1 - rejected
G2 - approved
G3 - approved
G4 - approved
G5 - approved

4 个答案:

答案 0 :(得分:3)

您可以通过测试每个comment值是否以approvedrejected状态存在于grn-no中的行来进行此操作。如果grn未被批准或拒绝,则状态将设置为pending

SELECT g.`grn-no`,
       CASE WHEN EXISTS (SELECT * FROM comment c WHERE c.grn_id = g.id AND c.status = 'approved') THEN 'approved'
            WHEN EXISTS (SELECT * FROM comment c WHERE c.grn_id = g.id AND c.status = 'rejected') THEN 'rejected'
            ELSE 'pending' END AS status
FROM grn g    

输出:

grn-no  status
G1      rejected
G2      approved
G3      approved
G4      approved
G5      approved

Demo on dbfiddle

答案 1 :(得分:2)

您可以使用correlated subquery

select concat(grn_no,
              ' - ',
              coalesce((select status
                         from comment
                        where status = 'approved'
                          and grn_id = g.id
                        group by grn_id),
                       'rejected')) "Result"
  from grn g

Demo

答案 2 :(得分:2)

您可以使用group_concat(flatten)功能

Select
`grn-no`, 
Case when status like ('%approved%') then 'approved' else 'rejected' end as status 
From
(Select  
`grn-no`, 
 group_concat(status) as status 
 From grn 
 left join comment 
 on grn.id = comment.grn_id  
 group by 1) a

答案 3 :(得分:0)

最后,我找到了以下代码的所有功能。上面的问题是在下面开发数据库视图。

CREATE OR REPLACE VIEW summery AS

    SELECT
    g.id,
    g.supply_date,
    g.grn_no,
    COUNT(b.bag_no) AS bags,
    CONCAT(s.fname," ", s.lname) AS name,
    SUM(b.weight) AS qty,
    AVG(b.bag_mc) AS mc,
    (g.dust_initial/g.dust_weight)*100 AS dust,
    (g.ubs_initial/g.ubs_weight)*100 AS ubs,
    p.fraction_1 AS fraction_1,
       CASE
        WHEN EXISTS (SELECT * FROM comments c WHERE c.grn_id = g.id AND c.status = 'approved') THEN 'Approved'
        WHEN EXISTS (SELECT * FROM comments c WHERE c.grn_id = g.id AND c.status = 'approved with concession') THEN 'Approved with Concession'
        WHEN EXISTS (SELECT * FROM comments c WHERE c.grn_id = g.id AND c.status = 'concession required') THEN 'Concession Required'
        WHEN EXISTS (SELECT * FROM comments c WHERE c.grn_id = g.id AND c.status = 'rejected') THEN 'Rejected'
       ELSE 'pending' END AS status
FROM grns g
    JOIN suppliers s ON s.id = g.supplier_id
    JOIN psds p ON g.id = p.grn_id
    JOIN bags b ON g.id = b.grn_id
GROUP BY g.id
ORDER BY g.id DESC