select 1 random row with complex filtering

前端 未结 4 2014
死守一世寂寞
死守一世寂寞 2021-01-24 05:11

I\'ve 2 tables:

first table users:

+-------------------------+---------+------+-----+---------+-------+
| Field                   | Type             


        
4条回答
  •  孤独总比滥情好
    2021-01-24 06:05

    I've two problem solutions.

    1) With random id, from https://stackoverflow.com/a/4329447/2051938

    SELECT *
    FROM profiles AS r1
    JOIN
        (SELECT CEIL(RAND() *
                         (SELECT MAX(id)
                            FROM profiles)) AS id)
            AS r2
    WHERE
        r1.id >= r2.id
        AND
        r1.first_name IS NOT NULL
    AND
    NOT EXISTS (
        SELECT *
        FROM proposal
        WHERE
            proposal.to_id = r1.id
    )
    LIMIT 0 , 1
    

    2) With ORDER BY RAND()

    SELECT *
    FROM
        (
            SELECT *
            FROM profiles
            WHERE
                profiles.first_name IS NOT NULL
            ORDER BY RAND()
        ) AS users
    WHERE
        NOT EXISTS (
            SELECT *
            FROM proposal
            WHERE
                proposal.to_id = users.id
        )
    LIMIT 0 , 1
    

    First solution is faster but it've problem with "holes in id" and when you got id from the end (users may end earlier than there will be a match)

    Second solution is slower but without flaws!

提交回复
热议问题