I have this select statement:

select A.id,
    (select id from B order by rand() limit 1)b1,
    (select id from B where not id in(b1) order by rand() limit 1)b2,
    (select id from B where not id in(b1,b2) order by rand() limit 1)b3,
    (select id from B where not id in(b1,b2,b3) order by rand() limit 1)b4,
    (select id from B where not id in(b1,b2,b3,b4) order by rand() limit 1)b5
from A

It's not very fast, it doesn't give me an error, but also doesn't do what I want.

I want to read 5 random id's from Table B and connect them to Table A.

So far so good, i get a result with 5 id's from Table B, BUT there are doubles.

Even though i have this where clause that should prevent doubles, i get them.

For example A.id:1 has b1=1, b2=6, b3=1, b4=9, B5=3

I would understand if MySQL throws an error because it can't handle the statement, but there is nothing, so I think it should work, but it doesn't.

Anyone has an answer to this?

Edit: It doesn't matter if the result looks like this(subquery): 1:2,7,3,9,6 or like this(join): 1:2 1:7 1:3 1:9 1:6

As long as every A.id has different B.id's. It's ok for two or more A.Id's to have the same B.id's, but it should be coincidental.

Still the question why MySQL accepts the query and gives a wrong result.

有帮助吗?

解决方案

select id, b1, b2, b3, b4, b5
from (
    select A.id,
        @ := (select GROUP_CONCAT(DISTINCT id ORDER BY RAND()) AS ids from B),

        SUBSTRING_INDEX(SUBSTRING_INDEX(@, ',', 1), ',', -1) b1,
        SUBSTRING_INDEX(SUBSTRING_INDEX(@, ',', 2), ',', -1) b2,
        SUBSTRING_INDEX(SUBSTRING_INDEX(@, ',', 3), ',', -1) b3,
        SUBSTRING_INDEX(SUBSTRING_INDEX(@, ',', 4), ',', -1) b4,
        SUBSTRING_INDEX(SUBSTRING_INDEX(@, ',', 5), ',', -1) b5
    from A
) t

Example: http://sqlfiddle.com/#!2/d7df9/9

其他提示

Please check this post for selecting random rows: How to randomly select rows in SQL? You can then join those with the other table

SELECT B.id
FROM B JOIN A ON B.id=A.id
ORDER BY RAND()
LIMIT 5
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top