简体   繁体   English

MySQL右查询左连接图像表中的最新上传图像,并具有分页功能

[英]MySQL right query left join latest uploaded image from images table, with pagination

I'm trying to select few data from first table and only last uploaded image from images table. 我正在尝试从第一个表中选择一些数据,而从图像表中选择最后一个上传的图像。 My tables look like this: 我的表如下所示:

table named data_property has fields (columns): 名为data_property的表具有字段(列):

property_id, timestamp, label_town, label_sub, property_name, price_night, description (and others which I don't need in this case). property_id,时间戳,label_town,label_sub,property_name,price_night,描述(以及在这种情况下我不需要的其他信息)。

And table images with fields (columns): 以及带有字段(列)的表格图像:

image_id, property_id and ext. image_id,property_id和ext。 Images name is image_id and ext is extension of images. 图片名称是image_id,而ext是图片的扩展名。

Every property (property_id row) have 12 images in images table. 每个属性(property_id行)在images表中都有12张图像。 I need to join only last uploaded image per property and show 10 property ( $recordsize = 10 ) per page. 我只需要每个属性加入最后上传的图像,并每页显示10个属性( $recordsize = 10 )。 I don't know how to organize my query 我不知道如何组织查询

something like this: 像这样的东西:

SELECT 
    property_id, timestamp, label_town, label_sub, 
    property_name, price_night, description 
FROM 
    data_property 
    LEFT JOIN or INNER JOIN (image_id, property_id, ext 
ORDER BY image_id DESC LIMIT 1) 
    FROM images ORDER BY timestamp DESC LIMIT $recordstart, $recordsize

So, I need to select few field from data_property, join latest uploaded image which belong to that property, order by time of create property ad, sort from desc and show 10 property per page. 因此,我需要从data_property中选择几个字段,加入属于该属性的最新上传图像,按创建属性广告的时间排序,从desc排序,并在每页显示10个属性。

To get something like on this site: http://www.freehouseagent.com/property-for-sale/ireland/ 要在此网站上获得类似内容: http : //www.freehouseagent.com/property-for-sale/ireland/

Sorry for my bad English. 对不起,我的英语不好。 I hope that you understand me. 我希望你能理解我。 Thanks and Best regards! 谢谢,最好的问候!

try this: 尝试这个:

SELECT 
    p.property_id, p.timestamp, p.label_town, p.label_sub,  p.property_name,
    p.price_night, p.description, i.image_id, i.property_id, i.ext 
FROM 
    data_property as p
LEFT JOIN images as i
ON p.property_id = i.property_id
GROUP BY p.property_id
ORDER BY p.timestamp DESC
LIMIT 10

you can also try this for more accuracy: 您也可以尝试使用此方法以提高准确性:

SELECT 
    p.property_id, p.timestamp, p.label_town, p.label_sub,  p.property_name,
    p.price_night, p.description, i.image_id, i.property_id, i.ext 
FROM 
    data_property as p
LEFT JOIN (
            SELECT MAX(image_id) as max, property_id
            FROM
                images
            GROUP BY
                property_id
           ) as n
ON p.property_id = n.property_id
LEFT JOIN
  images as i
ON i.image_id = n.max AND i.property_id = n.property_id
ORDER BY p.property_id DESC
LIMIT 10

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM