RE: Random record

From: Gentry, Michael (michael_gentr..anniemae.com)
Date: Fri Oct 22 2004 - 16:59:23 EDT

  • Next message: Jason Vasquez: "Re: Random record"

    If you are using MySQL, you could convince it to help you out:

    SELECT * FROM table ORDER BY RAND()

    I think you'd need to use an SQLTemplate for that one, though. Maybe
    set a fetch limit, too, if you are only wanting one record. Since you'd
    already be using an SQLTemplate, I'd do it in SQL and not in Cayenne:

    SELECT * FROM table ORDER BY RAND() LIMIT 1

    I'm not sure which, if any, other databases support this. If you are
    not using MySQL or using a database which can do the same, the only
    thing that pops into my mind is to use an SQLTemplate to select all the
    primary keys out of the table you are wanting a random row from, and
    then choose one of those randomly in your code. You can then fetch the
    actual object using:

    DataObjectUtils.objectForPK(dataContext, MyObjEntity.class, randomPk)

    Good luck!

    /dev/mrg

    PS. If you have to fetch all the PKs to choose randomly, I'd make a
    helper class and cache them for efficiency purposes.

    -----Original Message-----
    From: Jason Vasquez [mailto:jaso..ugfu.com]
    Sent: Friday, October 22, 2004 2:20 PM
    To: cayenne-use..bjectstyle.org
    Subject: Random record

    Hi all:

    I've got an oddball question here...

    I'd like to randomly pick a record out of a table. I did
    this previously with JDBC/Scrollable ResultSets (pick a
    random number in the range of the number of rows, and jump
    around the ResultSet picking out records) I suppose I could
    still do this, and just obtain PKs to later load up DataObject's,
    but I was wondering if someone could think of something else?

    Can anyone offer any advice as to how such a thing could be
    accomplished with Cayenne?

    Thanks,
    Jason

    -- 
    



    This archive was generated by hypermail 2.0.0 : Fri Oct 22 2004 - 16:59:34 EDT