在某些列中返回NULL而不是重复值

时间:2016-01-12 19:06:20

标签: php mysql join left-join

我的查询必须允许某些列中的重复值,但我希望它在重复值出现时在查询中返回null。

以下两张图片显示了我的问题:

现在返回什么

enter image description here

我希望它返回:

enter image description here

SQL查询:

SELECT *
FROM completo_sem_saldo AS a
LEFT JOIN posicao_contabil AS b ON (a.Cliente = b.Cliente_Posicao)
LEFT JOIN saldo_analitico AS c ON (a.Cliente = c.Cliente_Saldo_Analitico)
LEFT JOIN titulos_em_ser AS d ON (a.Cliente = d.Cliente_Titulos_Em_Ser) 

2 个答案:

答案 0 :(得分:0)

您可以在PHP中使用执行重复检查的函数执行此操作,并在重复时返回“”:

function blankIfRepeat($result, $key, &$map) {
    if (isset($map[$key]) && $map[$key] == $result[$key]) {
        return ""; // it is the same value we encountered last time
    }
    $map[$key] = $result[$key];
    return $result[$key];
}

注意最后一个参数之前的&,以确保调用者获得对该参数所做的更改。

你这样使用它:

$map = array(); // initialise the variable used to track repetitions
while($resul1 = mysqli_fetch_assoc($query1)) {
    $nome = $resul1['Nome'];
    // call the function for the fields that need blanks for repeated values:
    $sld_dev_ctbl = blankIfRepeat($resul1, 'Sld_dev_ctbl', $map);
    $saldo = blankIfRepeat($resul1, 'Saldo', $map);

    $vlr_atual = $resul1['Vlr_atual'];

    $tabela .= '<tr>';
    $tabela .= '<td>'.$nome.'</td>';
    $tabela .= '<td>'.$sld_dev_ctbl.'</td>';
    $tabela .= '<td>'.$saldo.'</td>';
    $tabela .= '<td>'.$vlr_atual.'</td>';
    $tabela .= '</tr>';
}
$tabela .= '</table>';

答案 1 :(得分:0)

USE变量仅显示第一行。

CASE的默认值为null,因此我没有包含ELSE

这假设没有负面的saldo,因此起始值为-1

SELECT CASE WHEN rn = 1 THEN Sld_dev_ctbl END as Sld_dev_ctbl,
       CASE WHEN rn = 1 THEN Saldo END as Saldo           
       Vlr_actual,
FROM ( 
        SELECT *,
               (@rownum := if( @saldo = Saldo,
                               @rownum + 1, -- increase the counter
                               if (@saldo := Saldo,
                                   0,  -- reset the counter for next block
                                   0
                                  )
                             )
               ) as rn
        FROM completo_sem_saldo AS a
        LEFT JOIN posicao_contabil AS b ON (a.Cliente = b.Cliente_Posicao)
        LEFT JOIN saldo_analitico AS c ON (a.Cliente = c.Cliente_Saldo_Analitico)
        LEFT JOIN titulos_em_ser AS d ON (a.Cliente = d.Cliente_Titulos_Em_Ser) 
        CROSS JOIN (select @rownum := 0, @saldo := -1) params
        ORDER BY --<provide some field to choose which one will be first>
) T