我需要一些帮助来解决查询

我有3张桌子

sources
id, name, rank

origin
id, source_id (FK to sources id), name

One source can have many origins

product
id, origin_id (FK to origin id), name, time_added

One origin can have many products


现在,我要选择的是每个来源的最新产品,按降序排列

有什么建议么?

最佳答案

这应该按照您的要求进行,但是如果没有样本输出,很难100%确定。内部查询会选择链接到源ID的产品(按从最新到最早的添加日期排序),然后依次将这些产品加入到源中并进行分组。

SELECT
  *
FROM sources AS s
INNER JOIN (
    SELECT
        origins.source_id,
        product.*
     FROM origin
     INNER JOIN product
     ON product.origin_id = origin.origin_id
     ORDER BY time_added DESC
) AS productsOrdered
ON productsOrdered.source_id = sources.source_id

ORDER BY s.rank DESC, productsOrdered.time_added DESC


由于内部选择应该非常快,并且可以根据需要进行限制,因此避免了执行昂贵的操作的麻烦

关于mysql - mysql高级组查询,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9326843/

10-11 05:20