在mysql中获取前一条记录是按值排序的,而不是按索引排序的(MySQL5.6.40)

lp0sw83n  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(270)

假设我有一张table 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 |

现在假设我有一个查询做了一个类似的搜索。例如。: SELECT id, time_end FROM fruit WHERE text LIKE '%tree'; 那会给我 banana tree , pear tree ,和 apple 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 |
ht4b089n

ht4b089n1#

你可以这样做:
sql小提琴
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'

结果:

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

相关问题