假设我有一个这样的表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搜索。例如。:
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 |
答案 0 :(得分:1)
您可以这样:
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 |