发布帖子Select distinct ordered pair from table join
如何选择按订购对分组的最新约翰加入行,无论顺序如何(例如John - > Jane或Jane - > John)?
第一张表:
table_a
+-----------+--------------+-------------------+
| id | name | created_at |
+-----------+--------------+-------------------+
| 1 | John |2016-08-26 15:40:21|
+-----------+--------------+-------------------+
| 2 | Jane |2016-08-26 15:37:21|
+-----------+--------------+ ------------------+
| 3 | Jane |2016-08-26 15:38:21|
+-----------+--------------+-------------------+
| 4 | Tara |2016-08-26 15:39:21|
+-----------+--------------+-------------------+
第二张表:
table_b
+-----------+-------------------+-------------+-------------+
| id | id_table_a | name | message |
+-----------+-------------------+-------------+-------------+
| 1 | 1 | Jane | Test 1 |
+-----------+-------------------+-------------+-------------+
| 2 | 2 | John | Test 2 |
+-----------+-------------------+-------------+-------------+
| 3 | 3 | Sammy | Test 3 |
+-----------+-------------------+-------------+-------------+
| 4 | 4 | John | Test 4 |
+-----------+-------------------+-------------+-------------+
一个可能的结果
+-----------+-------------+-------------+-------------+-------------------+
| id | name_a | name_b | message | created_at |
+-----------+-------------+-------------+-------------+-------------------+
| 1 | John | Jane | Test 1 |2016-08-26 15:40:21|
+-----------+-------------+-------------+-------------+-------------------+
| 4 | Tara | John | Test 4 |2016-08-26 15:39:21|
+-----------+-------------+-------------+-------------+-------------------+
非常感谢!
答案 0 :(得分:0)
试试这个:
(select a.id, a.name, b.name, b.message, a.created_at from a left join b on a.id=b.aid where a.name='John' order by a.created_at desc limit 1)
union all
(select a.id, a.name, b.name, b.message, a.created_at from a left join b on a.id=b.aid where b.name='John' order by a.created_at desc limit 1)
答案 1 :(得分:0)
这有点乱。以下是使用user-defined variables
在每组结果中建立row_number
然后按行号= 1过滤的选项:
select *
from (
select *,
@rn := if(@prev_name_a = name_a and @prev_name_b = name_b, @rn+1,
if(@prev_name_a:=name_a,1,
if(@prev_name_b:=name_b, 1, 1)
)
) rn
from (
select least(a.name, b.name) as name_a,
greatest(a.name, b.name) as name_b,
a.created_at,
a.id,
b.message
from table_a a
join table_b b on a.id = b.id_table_a
) t cross join (select @rn:=0, @prev_name_a:=null, @prev_name_b:=null) t1
order by name_a, name_b, created_at desc
) t
where 'John' in (name_a, name_b) and rn = 1