select 每组2行之间

select between 2 rows of each group

-- phpMyAdmin SQL Dump
-- version 4.7.9
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Aug 03, 2018 at 12:20 PM
-- Server version: 10.1.31-MariaDB
-- PHP Version: 7.2.3

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;

--
-- Database: `items`
--

-- --------------------------------------------------------

--
-- Table structure for table `tests`
--

CREATE TABLE `tests` (
  `ID` int(4) NOT NULL,
  `SID` int(4) NOT NULL,
  `VID` int(4) NOT NULL,
  `Text` varchar(20) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

--
-- Indexes for dumped tables
--

--
-- Indexes for table `tests`
--
ALTER TABLE `tests`
  ADD PRIMARY KEY (`ID`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `tests`
--
ALTER TABLE `tests`
  MODIFY `ID` int(4) NOT NULL AUTO_INCREMENT;
COMMIT;

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

我明白了,但我不知道如何将它们搭配在一起:

select 两行之间:

SELECT
    MAX(`VID`)-3 AS max1,
    MAX(`VID`)-2 AS max2
FROM `tests`
GROUP BY `SID`

return行的值:

SELECT *
FROM `tests`
WHERE `VID`>='max1' AND `VID`<='max2'
ORDER BY `SID` ASC, `VID` ASC

结果应该是这样的:

**Group:1**

test - 3

test - 4

**Group:2**

test - 283

test - 284

**Group:3**

test - 197

test - 198

**Group:4**

test - 173

test - 174

**Group:5**

test - 117

test - 118

**Group:6**

test - 162

test - 163

**Group:7**

test - 203

test - 204

**Group:8**

test - 72

test - 73

**Group:9**

test - 126

test - 127

**Group:10**

test - 106

test - 107

您可以将 table 与包装在子查询中的聚合结合起来:

    SELECT t.*
      FROM tests t
      JOIN (
                SELECT SID
                     , MAX(VID)-3 AS max1
                     , MAX(VID)-2 AS max2
                  FROM tests
              GROUP BY SID
           ) tagg
        ON tagg.SID = t.SID
     WHERE t.VID >= tagg.max1
       AND t.VID <= tagg.max2
  ORDER BY t.SID
         , t.VID
         ;