SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Wizard Darren884's Avatar
    Join Date
    Aug 2003
    Location
    Southern California, United States
    Posts
    1,616
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Random Query Help

    How would I do a random query where a row would be chosen from one table but the chances of it being chosen would be determined by the count of rows that relates to that tables ID in another table? Is this possible in mysql?

    Example:
    Table to be chosen from
    name_id|name
    1|Harold
    2|Glen
    3|Jessica

    Other table posts
    post_id|name_id|comment
    1|2|hello
    2|3|cool
    3|1|sup
    4|2|hi

    Where Glen would have a better chance of being chosen randomly then the other two because he had 2 rows in the table posts.

    Is this possible? Thank you.
    Have a good day.

  2. #2
    SitePoint Guru
    Join Date
    Jan 2004
    Location
    Uppsala, sverige
    Posts
    696
    Mentioned
    2 Post(s)
    Tagged
    1 Thread(s)
    Code:
    select name
    from nameTable nt
     left join otherTable ot on nt.name_id = ot.name_id
    order by rand()
    limit 1


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •