简体   繁体   中英

mysql update query to set field with id's of another table

I have 3 tables in database

1) videos.

id    name
1     one
2     two
3     three

2) session_has_video.

session_id    video_id
1             1
1             3

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 . It means it should be 1,3

So, updated table should look like this

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?

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. Then do a SET on the channel_has_session table using this CSV list. 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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM