更新mysql select into insert语句

时间:2013-10-31 09:40:12

标签: mysql sql sql-update inner-join

我有以下表格:

文件

| id  | title             | authors |
-------------------------------------
| 1   | Arms and the Man  |         |
| 2   | East of Eden      |         |
| 3   | If Not Now, When? |         |

作者

| id  | initial | lastname     |
--------------------------------
| 1   | J       | Bloggs       |
| 2   | J       | Doe          |
| 3   | P       | Punchclock   |
| 4   | D       | Botts        |

的著者

| id  | document_id  | author_id |
----------------------------------
| 1   | 1            | 1         |
| 2   | 1            | 2         |
| 3   | 1            | 3         |
| 4   | 2            | 3         |
| 5   | 2            | 4         |
| 6   | 3            | 1         |
| 7   | 3            | 3         |
| 8   | 3            | 4         |

我有以下sql语句:

select d.id, d.title, 
group_concat(concat(a.lastname,', ', a.initial, '.') 
             order by a.lastname, a.initial separator ' ') authors
from documents d
inner join authorships ash on ash.document_id = d.id
inner join authors a on ash.author_id = a.id
group by d.id, d.title

返回以下结果:

| id  | title             | authors                             |
-----------------------------------------------------------------
| 1   | Arms and the Man  | Bloggs, J. Doe, J. Punchclock, P.   |
| 2   | East of Eden      | Punchclock, P. Botts, D.            |
| 3   | If Not Now, When? | Bloggs, J. Punchclock, P. Botts, D. |

我需要将select转换为update语句,该语句使用SQL语句中显示的结果更新documents表中的authors列。

我猜我需要以某种方式在一个更新语句中嵌入select语句?这是我尝试过的,虽然不正确:

update p set authors = group_concat(concat(a.lastname,', ', a.initial, '.') 
             order by a.lastname, a.initial separator ' ')
from documents d
inner join authorships ash on ash.document_id = d.id
inner join authors a on ash.author_id = a.id
group by d.id, d.title

1 个答案:

答案 0 :(得分:0)

我真的建议你用这个“计算数据”创建一个View,而不是试图把这个非规范化的值放在你的表中,如果你真的想在db中有这些值。如果你不这样做,你将不得不创建触发器来保持这些值“最新”,并且你会使你的生活过于复杂。

现在,对于“理论解决方案”

UPDATE documents base_d
inner join
  (select d.id, d.title, 
   group_concat(concat(a.lastname,', ', a.initial, '.') 
             order by a.lastname, a.initial separator ' ') authors
   from documents d
   inner join authorships ash on ash.document_id = d.id
   inner join authors a on ash.author_id = a.id
   group by d.id, d.title) as d1
 on base_d.id = d1.id
 set base_d.authors = d1.authors;

视图解决方案:

create view v_documents_withAuthors as
(select d.id, d.title, 
group_concat(concat(a.lastname,', ', a.initial, '.') 
             order by a.lastname, a.initial separator ' ') authors
from documents d
inner join authorships ash on ash.document_id = d.id
inner join authors a on ash.author_id = a.id
group by d.id, d.title)

请参阅SqlFiddle

相关问题