且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Mysql left join 从结果中删除重复值

更新时间:2022-11-30 17:01:28

left join users u2在 t.user_2 = u2.id AND u2.id u1.id

在 u2 的左连接中,只需告诉查询检查 u2.id != u1.id.

我认为它应该可以解决您的问题.

I have two tables. users table and a comments table.

Please the schema and demo http://sqlfiddle.com/#!9/e3269c/5

Please see the image

In the first row, you can see that the query returns user_1_id = 2 and user_2_id = 2 Here I want to get only two maximum users but they have to be unique. So in this case, user_2_id should be null and other field of user_2 as well.

  1. If two unique ids is not found, then return only one, and rest can be null like you see in row 4.
  2. If same ids are found multiple time like in the first row, then only once they should be retrieved.

Thank you so much. Its a second question from the original question MySQL group by with left join

left join users u2 on t.user_2 = u2.id AND u2.id <> u1.id

In the left join of u2 just tell the query to check that u2.id != u1.id.

I think it should solve your provlem.