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

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

假设我有一张table fruit 这样地:

  1. | text | id | time_end | parent_id |
  2. | ------------|----|----------|-----------|
  3. | banana tree | 23 | 200 | 7 |
  4. | tomato vine | 84 | 500 | 7 |
  5. | pear tree | 13 | 800 | 7 |
  6. | apple tree | 40 | 1000 | 7 |
  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 . 如何在最少的查询数下做到这一点?在此示例中,输出应为:

  1. | text | id | time_end | time_start | parent_id |
  2. |-------------|----|----------|------------|-----------|
  3. | banana tree | 23 | 200 | 0 | 7 |
  4. | pear tree | 13 | 800 | 500 | 7 |
  5. | apple tree | 40 | 1000 | 800 | 7 |
ht4b089n

ht4b089n1#

你可以这样做:
sql小提琴
mysql 5.6架构设置:

  1. CREATE TABLE fruit
  2. (`text` varchar(11), `id` int, `time_end` int, `parent_id` int)
  3. ;
  4. INSERT INTO fruit
  5. (`text`, `id`, `time_end`, `parent_id`)
  6. VALUES
  7. ('banana tree', 23, 200, 7),
  8. ('tomato vine', 84, 500, 7),
  9. ('pear tree', 13, 800, 7),
  10. ('apple tree', 40, 1000, 7),
  11. ('grape vine', 15, 1800, 7)
  12. ;

查询1:

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

结果:

  1. | text | id | time_end | time_start | parent_id |
  2. |-------------|----|----------|------------|-----------|
  3. | banana tree | 23 | 200 | 0 | 7 |
  4. | pear tree | 13 | 800 | 500 | 7 |
  5. | apple tree | 40 | 1000 | 800 | 7 |
展开查看全部

相关问题