使用连接表SQL中的if条件确定列数据

时间:2016-04-07 19:33:53

标签: mysql sql-server

我有一个运行良好的查询,我想要的帮助是如何合并一个条件来确定给定列上显示的值。也就是说,如果一个表的列具有值" COA的授权"然后添加的列日期应显示该列应显示为空的日期

到目前为止,这是我的查询

SELECT r.request_id, r.product_name, r.created_at, r.can,a_s.stat, r.client_id, CONCAT(u.fname,' ',u.lname) 'analyst' , t.date_added (//should show the value of date_added else NULL based on a condition for this column),
    FROM request r
    LEFT OUTER JOIN assigned_samples a_s ON r.request_id = a_s.labref
    LEFT OUTER JOIN user u ON a_s.analyst_id = u.id
    LEFT OUTER JOIN tracking_table t ON r.request_id = t.labref
    WHERE r.client_id='$cid'
    AND r.created_at BETWEEN '$start' AND '$end'
    AND a_s.department_id = '$dept'
    GROUP BY r.request_id
    ORDER BY `r`.`created_at` DESC "

4 个答案:

答案 0 :(得分:1)

在这种情况下,一个简单的CASE陈述就足够了。我相信。

SELECT r.request_id, r.product_name, r.created_at, r.can,a_s.stat, r.client_id, 
CONCAT(u.fname,' ',u.lname) 'analyst', 
CASE WHEN ConditionColumn = 'Authorization of COA' THEN t.date_added 
ELSE NULL END AS 'date_added' 
    FROM request r
    LEFT OUTER JOIN assigned_samples a_s ON r.request_id = a_s.labref
    LEFT OUTER JOIN user u ON a_s.analyst_id = u.id
    LEFT OUTER JOIN tracking_table t ON r.request_id = t.labref
    WHERE r.client_id='$cid'

答案 1 :(得分:0)

在mysql和ms sql中,您可以使用case表达式(mysql case; ms sql case)有条件地为字段赋值:

SELECT r.request_id, r.product_name, r.created_at, r.can,a_s.stat, r.client_id, CONCAT(u.fname,' ',u.lname) 'analyst' , 
    CASE WHEN Column_To_Test = 'Authorization of COA' THEN t.date_added
        ELSE null
    END AS date_added 
    FROM request r
    LEFT OUTER JOIN assigned_samples a_s ON r.request_id = a_s.labref
    LEFT OUTER JOIN user u ON a_s.analyst_id = u.id
    LEFT OUTER JOIN tracking_table t ON r.request_id = t.labref
    WHERE r.client_id='$cid'
    AND r.created_at BETWEEN '$start' AND '$end'
    AND a_s.department_id = '$dept'
    GROUP BY r.request_id
    ORDER BY `r`.`created_at` DESC "

这样,解决方案在数据库之间更具可移植性。 Mysql提供if()函数,ms sql iif()来实现上述功能,但这些都是产品特定的解决方案。

答案 2 :(得分:0)

尝试使用Case语句,如。

  

案例 Condition_1 AND Condition_2 或...... Condition_N 那么(Value_1) ELSE (Value_1)结束

此处条件 _1可以是列记录值及其列记录值的组合 和 _1可以是单值[Ex:Null或“some string”]或嵌套sql语句中的返回值,如[Ex :(从...中选择计数(*)]

答案 3 :(得分:-1)

尝试一下:

SELECT r.request_id, r.product_name, r.created_at, r.can,a_s.stat, r.client_id, CONCAT(u.fname,' ',u.lname) 'analyst' , 
IFF(nameOfColumnToTest = 'Authorization of COA', t.date_added, null) AS DateAdded 
    FROM request r
    LEFT OUTER JOIN assigned_samples a_s ON r.request_id = a_s.labref
    LEFT OUTER JOIN user u ON a_s.analyst_id = u.id
    LEFT OUTER JOIN tracking_table t ON r.request_id = t.labref
    WHERE r.client_id='$cid'
    AND r.created_at BETWEEN '$start' AND '$end'
    AND a_s.department_id = '$dept'
    GROUP BY r.request_id
    ORDER BY `r`.`created_at` DESC "