I’m trying to randomly grab about 20 random rows from a table, then using the INNER JOIN command, add about 7 columns of additional data to those rows from a different table based on a common ID.
The database contains 2 tables, the first (listings) is indexed by id (which has holes), the second (listingselements) has 7 field_name/field_value pairs for each id in the first table. I’m interested in 5 of them.
I can’t wrap my head around how to do it. Can it be done in the database, or should it be done in multiple queries programmatically?
SELECT listings.id, listings.title, listings.featured, listingselements.field_name, listingselements.field_value
FROM listings
INNER JOIN listingselements
ON listings.id = listingselements.id
WHERE RAND()<(SELECT ((20/COUNT(*))*10) FROM listings)
AND (listingselements.field_name = "price"
OR listingselements.field_name = "bathrooms"
OR listingselements.field_name = "bedrooms"
OR listingselements.field_name = "sq_meter"
OR listingselements.field_name = "city")
ORDER BY RAND();
The WHERE/ORDER BY RAND() works great, however the query doesn’t grab the INNER JOIN columns before moving on to the next item.
try to put the random 20 percent into a inner select in the from clause