将MySQL中的上一条记录按值排序,而不是按索引排序(MySQL 5.6.40)

问题描述 投票:0回答:1

假设我有一张像这样的桌子fruit

|        text | id | time_end | parent_id |
| ------------|----|----------|-----------|
| banana tree | 23 |      200 |         7 |
| tomato vine | 84 |      500 |         7 |
|   pear tree | 13 |      800 |         7 |
|  apple tree | 40 |     1000 |         7 |
|  grape vine | 15 |     1800 |         7 |

现在假设我有一个执行LIKE搜索的查询。 E.G。:SELECT id, time_end FROM fruit WHERE text LIKE '%tree';

那会给我banana treepear treeapple tree的数据。

但是假设我想要每行之前的数据,使用time_end + parent_id的双列索引。如何以最少的查询数量完成此操作?在此示例中,输出应为:

|        text | id | time_end | time_start | parent_id |
|-------------|----|----------|------------|-----------|
| banana tree | 23 |      200 |          0 |         7 |
|   pear tree | 13 |      800 |        500 |         7 |
|  apple tree | 40 |     1000 |        800 |         7 |
mysql
1个回答
1
投票

你可以这样做:

SQL Fiddle

MySQL 5.6架构设置:

CREATE TABLE fruit
    (`text` varchar(11), `id` int, `time_end` int, `parent_id` int)
;

INSERT INTO fruit
    (`text`, `id`, `time_end`, `parent_id`)
VALUES
    ('banana tree', 23, 200, 7),
    ('tomato vine', 84, 500, 7),
    ('pear tree', 13, 800, 7),
    ('apple tree', 40, 1000, 7),
    ('grape vine', 15, 1800, 7)
;

查询1:

 SELECT a.text,a.id, a.time_end,
 IFNULL((select max(time_end) from fruit where time_end < a.time_end),0) as time_start,
 a.parent_id 
 FROM fruit a WHERE a.text LIKE '%tree'

Results

|        text | id | time_end | time_start | parent_id |
|-------------|----|----------|------------|-----------|
| banana tree | 23 |      200 |          0 |         7 |
|   pear tree | 13 |      800 |        500 |         7 |
|  apple tree | 40 |     1000 |        800 |         7 |
© www.soinside.com 2019 - 2024. All rights reserved.