加入相同的table时,如何将加入的数据放在不同的行而不是不同的列?

When joining the same table, how to put the joined data in separate rows rather than separate columns?

假设,我有如下查询。

select * from `Students` s1
join `Students` s2
on s2.id = s1.id + 1 and s2.marks >= 80 and s1.marks >= 80

在这种情况下,s1s2 的数据将被放入两个单独的列中,但我怎样才能将它们放入单独的行中呢?

这是一个示例数据:

+---+------+
| id| marks| 
+---+------|
| 1 | 88   |
| 2 | 77   |
| 3 | 81   |
| 4 | 82   |
| 5 | 75   |
| 6 | 80   |
| 7 | 90   |
| 8 | 93   |
+---+------+

我想要的是要显示两个连续 80+ 标记的行(按 id 排序)。例如,在这种情况下,将显示 ID 为 3、4、6、7 和 8 的行。

如前所述,在没有看到您的数据的情况下,我猜您可以在查询中使用 union

SELECT
  s1.*
FROM
  `students` s1
  JOIN students s2
    ON s2.id = s1.id + 1
    AND s2.marks >= 80
    AND s1.marks >= 80
UNION
SELECT
  s2.*
FROM
  `students` s1
  JOIN students s2
    ON s2.id = s1.id + 1
    AND s2.marks >= 80
    AND s1.marks >= 80
ORDER BY id;

如果您的 MySql 版本是 8.0+,您可以使用 LAG()LEAD() window 函数来检查 [=15= 的上一个和下一个值] 每行:

SELECT id, marks
FROM (
  SELECT *,
         LAG(marks) OVER (ORDER BY id) prev_marks,
         LEAD(marks) OVER (ORDER BY id) next_marks
  FROM students       
) t
WHERE marks >= 80 AND (prev_marks >= 80 OR next_marks >= 80)
ORDER BY id;

对于以前的版本使用 EXISTS:

SELECT s1.*
FROM students s1
WHERE s1.marks >= 80
AND EXISTS (
  SELECT 1 
  FROM students s2
  WHERE s2.id IN (s1.id - 1, s1.id + 1) AND s2.marks >= 80
)
ORDER BY s1.id;

或者,使用自连接:

SELECT DISTINCT s1.*
FROM students s1 INNER JOIN students s2
ON s2.id IN (s1.id - 1, s1.id + 1)
WHERE s1.marks >= 80 AND s2.marks >= 80
ORDER BY s1.id;

参见demo