[英]mysql update query to set field with id's of another table
I have 3 tables in database 我在数据库中有3个表
1) videos. 1)视频。
id name
1 one
2 two
3 three
2) session_has_video. 2)session_has_video。
session_id video_id
1 1
1 3
3) channel_has_session. 3)channel_has_session。
channel_id session_id videos
1 1
I want to update channel_has_session.videos
with all the video.id
where video.id
is in session.session_id
. 我想用
video.id
更新channel_has_session.videos
,其中video.id
在session.session_id
。 It means it should be 1,3
这意味着它应该是
1,3
So, updated table should look like this 因此,更新的表应该如下所示
channel_has_session. channel_has_session。
channel_id session_id videos
1 1 1,3
i tried this query, but obvious not working. 我试过这个查询,但显然没有工作。
update channel_has_session set videos = ( SELECT video_id FROM session_has_video where session_id=1 ) where session_id=1 and channel_id=1
Is there any easiest way to do like this in MySQL? 在MySQL中有这样的最简单方法吗?
You can join the channel_has_session
table to a temporary table containing each session_id
along with its comma-separated list of video_id
values. 您可以将
channel_has_session
表加入包含每个session_id
的临时表以及以逗号分隔的video_id
值列表。 Then do a SET
on the channel_has_session
table using this CSV list. 然后使用此CSV列表在
channel_has_session
表上执行SET
。 Try this query: 试试这个查询:
UPDATE
channel_has_session AS ch
INNER JOIN (
SELECT session_id, GROUP_CONCAT(video_id) AS videos
FROM session_has_video
GROUP BY session_id
) AS t on ch.session_id = t.session_id
SET ch.videos = t.videos
WHERE ch.channel_id = 1 AND ch.session_id = 1
One way you can achieve it would be by using the group_concat()
function, as: 实现它的一种方法是使用
group_concat()
函数,如下所示:
UPDATE channel_has_session
SET videos = (
SELECT GROUP_CONCAT(DISTINCT video_id SEPARATOR ',')
FROM session_has_video
WHERE session_id = 1
)
WHERE session_id = 1 AND channel_id = 1
But, as said, using comma-separated values in your database is discouraged. 但是,如上所述,不建议在数据库中使用逗号分隔值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.