在每组的2行之间进行选择

ws51t4hk  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(279)
-- 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
    MAX(`VID`)-3 AS max1,
    MAX(`VID`)-2 AS max2
FROM `tests`
GROUP BY `SID`

返回行的值:

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
oaxa6hgo

oaxa6hgo1#

您可以使用 Package 在子查询中的聚合联接表:

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
         ;

相关问题