0

我有以下表格:

文件

| 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. |

我需要将我的选择转换为更新语句,该语句使用 SQL 语句中显示的结果更新文档表中的作者列。

我猜我需要以某种方式将 select 语句嵌入到 update 语句中?这是我尝试过的,虽然不正确:

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
4

1 回答 1

0

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

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

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

于 2013-10-31T09:51:50.883 回答