我正在尝试从表中随机抓取大约20个随机行,然后使用INNER JOIN命令,根据公共ID向不同表中的那些行添加大约7列附加数据。
数据库包含2个表,第一个(列表)由id(有孔)索引,第二个(listinglelements)为第一个表中的每个id有7个field_name / field_value对。我对其中的5个感兴趣。
我无法理解如何去做。可以在数据库中完成,还是应该以编程方式在多个查询中完成?
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();
WHERE / ORDER BY RAND()效果很好,但是在转到下一个项目之前,查询不会抓取INNER JOIN列。
答案 0 :(得分:0)
尝试将随机的20%放入from子句
中的内部选择中select inner_listings.id, inner_listings.title, inner_listings.featured,
listingselements.field_name, listingsdbelements.field_value
from
(SELECT listings.id, listings.title, listings.featured
FROM listings
WHERE RAND()<(SELECT ((20/COUNT(*))*10) FROM listings)
ORDER BY RAND()) inner_listings
inner join listingselements ON inner_listings.id = listingselements.id
where (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")