MySQL - 在INNER JOIN中订购IN

时间:2017-04-22 15:17:51

标签: mysql

我正在创建一个系统,允许用户在相册图像的数据库中搜索关键字,它工作得很好,唯一的问题是我按照关键字出现在相册中的次数来排序相关性。我是这样做的:

SELECT collections_ids.collection_id
 FROM `keywords`
 INNER JOIN collections_ids ON keywords.id = collections_ids.photo_id
 WHERE keywords.`keyword` = 'trees'
 GROUP BY collection_id
 ORDER BY COUNT(*) DESC

如上所述,这很有效。

唯一的问题是,当它包含在“WHERE IN”查询中时,它会丢失它的顺序并随机返回。为清楚起见,这是查询:

SELECT collections.id,
       collections.title
       images.img_small
FROM `collections`
INNER JOIN images ON images.id = collections.cover_photo
WHERE collections.`id` IN
    (SELECT collections_ids.collection_id
     FROM `keywords`
     INNER JOIN collections_ids ON keywords.id = collections_ids.photo_id
     WHERE keywords.`keyword` = 'trees'
     GROUP BY collection_id
     ORDER BY COUNT(*) DESC)

我尝试过研究,人们建议使用FIELD函数,但我没有看到在这种情况下工作。

有什么建议吗?

1 个答案:

答案 0 :(得分:1)

你可以使用子查询作为连接,并按照下面的顺序将其计数(*)

SELECT collections.id,
               collections.title
               images.img_small
        FROM `collections`
        INNER JOIN images ON images.id = collections.cover_photo
        INNER JOIN 
            (SELECT distinct collections_ids.collection_id As collection_id,COUNT(*) as total
             FROM `keywords`
             INNER JOIN collections_ids ON keywords.id = collections_ids.photo_id
             WHERE keywords.`keyword` = 'trees'
             GROUP BY collection_id
             ) as A
    ON A.collection_id =collections.collection_id
    order by A.total