如何获得具有最低图片编号的MySQL结果集?

时间:2016-05-16 15:52:21

标签: mysql sql

我需要从MySQL数据库中获取结果集,其中有多个图片引用每个项目。这些图片有一个picture_no字段,其中最低的数字是我想要返回的结果。

目前我正在使用此查询:

SELECT 
    ca.*,
    ca.ID AS ad_id,
    ca.cat_id,
    UNIX_TIMESTAMP(ca.date_edited) AS date,
    cp.*,
    ar.area_name
FROM  
    $DB.$T4 ca
        LEFT JOIN $T6 AS cp ON ca.ID = cp.classified_id AND cp.picture_no = 0 
        LEFT JOIN $T60  zip ON ca.zip_id = zip.zip_id
        LEFT JOIN $T3    ar  ON zip.area_id = ar.ID
WHERE
    ca.extern = 0
    AND ca.confirmed = 1
    AND ca.advertiser_id = ".$user['uid']."
ORDER BY 
    date_created        
LIMIT 10

正如您所看到的,我目前正在使用AND cp.picture_no = 0,因为我无法弄清楚如何获得最低数字的图片。

怎么可以这样做?函数min()没有帮助我解决问题。

3 个答案:

答案 0 :(得分:1)

你可以用这个:

SELECT 
    ca.*,
    ca.ID AS ad_id,
    ca.cat_id,
    UNIX_TIMESTAMP(ca.date_edited) AS date,
    cp.*,
    ar.area_name
FROM  
    $DB.$T4 ca
        LEFT JOIN (SELECT tmp.*
                   FROM $T6 tmp
                   INNER JOIN (SELECT classified_id, MIN(picture_no) min_picture_no
                               FROM $T6
                               GROUP BY classified_id) tmp1
                    ON tmp.classified_id = tmp1.classified_id 
                            and tmp.picture_no = tmp1.min_picture_no
                    ) AS cp 
        ON ca.ID = cp.classified_id
        LEFT JOIN $T60  zip ON ca.zip_id = zip.zip_id
        LEFT JOIN $T3   ar  ON zip.area_id = ar.ID
WHERE
    ca.extern = 0
    AND ca.confirmed = 1
    AND ca.advertiser_id = ".$user['uid']."
ORDER BY 
    date_created        
LIMIT 10

编辑:删除AND cp.picture_no = 0,因为它只是提问者的临时解决方案。感谢Paul Spiegel提出建议。

答案 1 :(得分:0)

您可以将联接更改为以下内容:

 LEFT JOIN (select * from $T6 AS cp where ca.ID = cp.classified_id order by picture_no asc limit 1) on ca.ID = cp.classified_id

答案 2 :(得分:0)

这不是最好的变体,但您可以替换:

LEFT JOIN $T6 AS cp ON ca.ID = cp.classified_id AND cp.picture_no = 0 

with:

LEFT JOIN $T6 AS cp ON ca.ID = cp.classified_id  
LEFT JOIN $T6 AS cp_temp 
ON cp_temp.ID = cp.classified_id 
 AND cp_temp.picture_no < cp.picture_no  

并在查询结尾处将AND cp_temp.id IS NULL添加到where子句。

所以最后的查询可能是这样的:

SELECT 
  ca.*,
  ca.ID AS ad_id,
  ca.cat_id,
  UNIX_TIMESTAMP(ca.date_edited) AS date,
  cp.*,
  ar.area_name
FROM  $DB.$T4 ca
LEFT JOIN $T6 AS cp 
ON ca.ID = cp.classified_id  
LEFT JOIN $T6 AS cp_temp 
ON cp_temp.ID = cp.classified_id 
  AND cp_temp.picture_no < cp.picture_no 
LEFT JOIN $T60  zip 
ON ca.zip_id = zip.zip_id
LEFT JOIN $T3   ar  
ON zip.area_id = ar.ID
WHERE ca.extern = 0
  AND ca.confirmed = 1
  AND ca.advertiser_id = ".$user['uid']."
  AND cp_temp.id IS NULL
ORDER BY date_created        
LIMIT 10