删除左表上的重复项,同时在右表SELECT JOIN上保留重复项

时间:2017-12-15 23:33:23

标签: mysql sql select join duplicates

我试图加入两个表并输出它们,这样我就不会从第一个表中获得任何重复项。在第一个表中,我没有重复,我加入了两个表,但在第二个表中可以有几个实例。

我试过" GROUP BY"在第一个表中的id,但当然消除了第二个表中的重复..

我应该尝试使用某种嵌套的SELECT,还是按照你的建议做什么?

似乎我被困住了,我会感激所有帮助。

这是我的问题:

$time_query = "SELECT time.id, time.time_in, time.time_out, time.comment, time.user_id, time_break.break_in AS break_in, time_break.break_out AS break_out, time_break.time_id AS time_id 
            FROM `time`
            LEFT JOIN time_break
            ON time.id = time_break.time_id
            WHERE time.time_out != '' AND time.user_id= $uid
            ORDER BY time.id ASC

1 个答案:

答案 0 :(得分:0)

我反对似乎"不自然"使用SQL操作结果,但是你可能会看到这里有多尴尬是一种抑制(或隐藏")你不想看到的值的方法。

在我看来,这应该在"表示层"上完成,但在MySQL中你可以使用变量来考虑以前的行值:

SELECT
      @row_num :=IF(@prev_value = t.id , @row_num + 1, 1) AS RowNumber
    , t.id
    , IF(@row_num = 1,t.id, '')       AS t_id
    , IF(@row_num = 1,t.time_in, '')  AS time_in
    , IF(@row_num = 1,t.time_out, '') AS time_out
    , IF(@row_num = 1,t.comment, '')  AS comment
    , IF(@row_num = 1,t.user_id, '')  AS user_id
    , tb.break_in                     AS break_in
    , tb.break_out                    AS break_out
    , tb.time_id                      AS time_id
    , @prev_value := t.id
FROM `time` AS t
LEFT JOIN time_break AS tb ON t.id = tb.time_id
CROSS JOIN (SELECT @row_num :=1,  @prev_value :='') vars
WHERE t.time_out <> ''
AND t.user_id = @UID
ORDER BY
      t.id ASC
    , t.time_in ASC
    , tb.break_in ASC

NB 使用此类查询的结果时,您应该按任何一些值被抑制/隐藏的列排序。