反向加入MySQL

所以,

问题

我的问题是 – 如何在MySQL中以相​​反的顺序连接自己的表?假设我有:

id  name
1   First
2   Second
5   Third
6   Fourth
7   Fifth
8   Sixth
9   Seventh
13  Eight
14  Nine
15  Tenth

– 现在我想创建一个查询,这将以相反的顺序返回已连接的记录:

left_id name    right_id    name 
   1    First      15   Tenth 
   2    Second     14   Nine 
   5    Third      13   Eight 
   6    Fourth      9   Seventh 
   7    Fifth       8   Sixth 
   8    Sixth       7   Fifth 
   9    Seventh     6   Fourth 
  13    Eight       5   Third 
  14    Nine        2   Second 
  15    Tenth       1   First 

我的做法

我现在有这个查询:

SELECT 
  l.id AS left_id, 
  l.name, 
  (SELECT COUNT(1) FROM sequences WHERE id<=left_id) AS left_order, 
  r.id AS right_id,
  r.name,
  (SELECT COUNT(1) FROM sequences WHERE id<=right_id) AS right_order 
FROM 
  sequences AS l 
  LEFT JOIN 
    sequences AS r ON 1
HAVING
  left_order+right_order=(1+(SELECT COUNT(1) FROM sequences));

– 这个fiddle用于样品结构&码.

一些背景

没有用例.我以前在申请过.现在,如果有一种方法可以在SQL中实现,那么这就是为什么我不仅仅是寻求“任何解决方案”(像我的),而且尽可能简单的解决方案.源表将始终是小的(<10.000条记录) - 所以表现不是一件值得关注的事情,我想. 问题 我的查询是否可以简化?此外,重要的是不要使用变量.订单可以包含在结果中(像我的小提琴) – 但这不是强制性的.

我唯一可以想到要改进的是

SELECT 
  l.id AS left_id, 
  l.name ln, 
  (SELECT COUNT(1) FROM sequences WHERE id<=left_id) AS left_order, 
  r.id AS right_id,
  r.name rn,
  (SELECT COUNT(1) FROM sequences WHERE id>=right_id) AS right_order 
FROM 
  sequences AS l 
  LEFT JOIN 
    sequences AS r ON 1
HAVING
  left_order=right_order;

有两个更改应该使这一点更快:

1)首先以相反的顺序计算正确的顺序

2)避免在最后一行使用SELECT COUNT.

编辑:我弄了ln,rn,因为我看不到小提琴的列

翻译自:https://stackoverflow.com/questions/19114308/reverse-join-in-mysql

转载注明原文:反向加入MySQL