MySQL query with RAND() subquery condition

2019-07-13 13:57发布

I have a nested subquery that selects a random AlbumID that the selected video is in (videos can be in multiple albums), and the outer query then returns the videos and album information based on that AlbumID.

The problem is that the query is returning mixed results; sometimes it gives me some of the videos from one album, sometimes it gives videos from multiple albums, sometimes it returns nothing.

The outer query works if I specify a specific AlbumID instead of the subquery, and the subquery by itself correctly returns 1 random AlbumID. But put together, it's giving me mixed results. What am I missing? Why is it returning varying amounts of rows, and multiple albums?

I've replicated the issue with test data, you can find the CREATE queries here: http://pastebin.com/raw.php?i=e6HaaSGK

The SELECT SQL:

SELECT  
    Videos_Demo.VideoID,
    VideosInAlbums_Demo.AlbumID
FROM 
    VideosInAlbums_Demo
    LEFT JOIN
        Videos_Demo
        ON Videos_Demo.VideoID = VideosInAlbums_Demo.VideoID
WHERE
    VideosInAlbums_Demo.AlbumID = (
                                    SELECT
                                        AlbumID
                                    FROM
                                        VideosInAlbums_Demo
                                    WHERE
                                        VideoID = '1'
                                    ORDER BY
                                        RAND()
                                    LIMIT 1
                                    )

1条回答
狗以群分
2楼-- · 2019-07-13 14:31

Try this. Moving the subquery to the JOIN seems to fix the problem. I think the problem has to do with having the subquery in the WHERE clause. I think that in the WHERE clause, the subquery and RAND function is being getting executed for each record. This is probably why the results are varying.

SELECT  a.AlbumID,
        Videos_Demo.VideoID,
        VideosInAlbums_Demo.AlbumID

FROM    VideosInAlbums_Demo

        LEFT JOIN Videos_Demo
        ON Videos_Demo.VideoID = VideosInAlbums_Demo.VideoID

        JOIN 
        (
            SELECT  AlbumID
            FROM    VideosInAlbums_Demo
            WHERE   VideoID = '1'
            ORDER BY RAND()
            LIMIT 1
        ) AS a ON VideosInAlbums_Demo.AlbumID = a.AlbumID
查看更多
登录 后发表回答