himanshu archirayan
himanshu archirayan

Reputation: 223

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?

Upvotes: 3

Views: 1340

Answers (2)

user098
user098

Reputation: 89

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.

Upvotes: 0

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522171

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

Upvotes: 2

Related Questions