select 1 random row with complex filtering

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

I\'ve 2 tables:

first table users:

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


        
4条回答
  •  天涯浪人
    2021-01-24 05:54

    As RAND() function assigns a random number to every row present in result, performance will be directly proportional to number of records.

    If you want to select only one (random) record, you can apply LIMIT , 1

    e.g.:

    SELECT u.id, count(u.id) as `count`
    FROM users u
    WHERE
        first_name IS NOT NULL
    AND
    NOT EXISTS (
        SELECT *
        FROM proposal
        WHERE
            proposal.to_id = u.id
    )
    LIMIT RAND(0, count-1) , 1
    

    I haven't tried executing this query, however, it MySQL complains about using count in RAND, you can calculate count separately and substitute the value in this query.

提交回复
热议问题