php - 在每组的 2 行之间选择

标签 php mysql sql database myisam

-- 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

最佳答案

您可以将表与包含在子查询中的聚合连接起来:

    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
         ;

关于php - 在每组的 2 行之间选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51670123/

相关文章:

php - INT(10) 和 INT(12) 之间有什么区别(应用于我的代码时)?

javascript - Google Contacts API - 如何仅过滤电子邮件联系人

php - 空 _FILES 变量

php - $_SESSION 不携带跨 php 页面

mysql - SQL 中多表的多重计数

SQL 字符串连接到表

php - 找不到 Laravel 4 迁移基表

php - 如何使用多个字段使用表单中的数据搜索 MySQL 数据库

mysql - 预订 : I want to display all records with a condition including if the record is null in table number 2

mysql - 连接两个表并选择第二个表中不存在的行 1