在来自不同行的不同列的CONCAT数据之后插入INTO

时间:2013-08-14 15:44:49

标签: php mysql sql

所以,我有这个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中)whoooole表,其中'next_line'和'raw_line'连接并按ID asc排序,但我尝试做这也是令人沮丧的失败,总是将'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新手。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分: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 here

答案 1 :(得分: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 demo

唯一稍微复杂的位是模数(%)和记录数,以便rawlines中的最后一个ID将加入nextlines的第一个ID。