3

所以,我有这个 MySQL 表。以下是相关列:

| raw line             | composed_line | next_line              
|----------------------|---------------|------------------------
|                      |               | When I have a bad day,
| I cry my eyes out.   |               | When I cry my eyes out,
| I get ice cream.     |               | When I get ice cream,    
| Things seem better.  |               | When things seem better,     
| I get out of bed.    |               | When I get out bed, 

我有这个查询,它可以做我想做的事情——它从倒数第二行的“下一行”列中选择数据,并将其与最近行的“raw_line”列中的数据结合起来。

SELECT CONCAT((SELECT `next_line` FROM `lines` ORDER BY id DESC LIMIT 1 OFFSET 1), 
(SELECT `raw_line` FROM `lines` ORDER BY id DESC LIMIT 1))

所以结果看起来像

When things seem better, I get out of bed.

但是,我所有尝试获取此结果并将其插入最近一行的名为“composed_line”的列中都失败了。我曾尝试使用 PHP 和 SQL 来执行此操作,但都不起作用。

如果我能想出一种方法来显示(在 PHP 中)带有 'next_line' 和 'raw_line' 并按 ID asc 排序的 whoooole 表,我就不需要这样做,但我尝试这样做也有令人沮丧的失败,总是一起显示'next_line',然后一起显示'raw_lines',或者其他一些不需要的糟糕结果(doublesadface)。

我想要的结果如下:

When I have a bad day, I cry my eyes out.
When I cry my eyes out, I get ice cream.
When I get ice cream, things seem better.
When things seem better, I get out of bed.

我是 SQL 的新手。任何帮助将非常感激。

4

2 回答 2

2

假设您有一个“id”列,最好将它与连接一起使用:

update line a
  join line b on a.id = b.id-1
  set a.composed_line = concat(a.next_line,' ',b.raw_line)
where b.raw_line is not null;

或者,只是显示它:

select
    concat(a.next_line,' ',b.raw_line)
from
   line a
   join line b on a.id = b.id-1

SQLFiddle在这里

于 2013-08-14T16:12:25.180 回答
1
SELECT CONCAT(nextlines.next_line, rawlines.raw_line) AS line
FROM `lines` rawlines
JOIN `lines` nextlines
ON rawlines.id = (nextlines.id % (SELECT COUNT(*) FROM `lines`)) + 1
ORDER BY rawlines.id ASC

请参阅SQL Fiddle 演示

唯一稍微复杂的位是带有记录数的模数 ( %),因此最后一个 IDrawlines将连接到来自 的第一个 ID nextlines

于 2013-08-14T16:15:21.973 回答