[英]update mysql select into insert statement
我有以下表格:
單據
| 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
我真的建議您使用此“計算數據”創建一個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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.