Return NULL 而不是某些列中的重复值

Return NULL instead of repeated value in certain columns

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

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

现在return是什么

我想要什么return:

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) 

您可以在 PHP 中使用执行重复检查和 returns "" 重复检查的函数来执行此操作:

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>';

使用变量仅显示第一行。

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