防止左连接上的重复项与MySQL中的内连接相结合

时间:2017-01-19 07:51:02

标签: mysql sql join left-join

这是我的sql。如果matches_times表中有重复的条目

,我无法过滤掉查询中的重复项
SELECT
  info.user_id,
  info.name,
  info.age,
  info.gender,
  DATE_FORMAT(likes.time, '%c/%e/%y') AS matchedTime,
  DATE_FORMAT(matches_times.proposed_time, '%b %d, %Y @ %h:%i %p') AS proposedTime,
    matches_times.agreed
FROM info
INNER JOIN likes
  ON info.user_id = likes.liked_user_id
  AND likes.user_id = ?
LEFT JOIN matches_times
  ON (info.user_id = matches_times.user_id_1 OR info.user_id = matches_times.user_id_2)
  AND (matches_times.user_id_1 = ? OR matches_times.user_id_2 = ?)
WHERE likes.liked_user_id IN (SELECT
  user_id
FROM likes
WHERE likes.liked_user_id = ?)
ORDER BY
    CASE 
      WHEN matches_times.proposed_time IS NULL THEN likes.time 
      WHEN matches_times.proposed_time IS NOT NULL THEN matches_times.proposed_time
    END DESC

这三个表格如下:

喜欢

id(pk) | user_id | liked_user_id | timestamp

信息

id(pk) | user_id | name | age | gender | timestamp

matches_times

id(pk) | user_id_1 | user_id_2 | proposed_time | agreed | timestamp

修改

问题在这里描述

enter image description here

1 个答案:

答案 0 :(得分:1)

一种简单的方法是基于这样一个事实,你可以使用具有不同的子选择(o等效视图)

LEFT JOIN (

    select distinct user_id_1, user_id_2,  DATE_FORMAT(proposed_time, '%b %d, %Y @ %h:%i %p') as proposed_time
    from matches_times

) t  ON (info.user_id = t.user_id_1 OR info.user_id = t.user_id_2)
  AND (t.user_id_1 = ? OR t.user_id_2 = ?)

并在select中引用t.proposed_time

如果你需要最大值,你不需要区别,但你需要分组,例如:

LEFT JOIN (

    select  user_id_1, user_id_2,  max(DATE_FORMAT(proposed_time, '%b %d, %Y @ %h:%i %p')) as proposed_time
    from matches_times
    group by user_id_1, user_id_2

) t  ON (info.user_id = t.user_id_1 OR info.user_id = t.user_id_2)
  AND (t.user_id_1 = ? OR t.user_id_2 = ?)