mysql高级组查询

时间:2012-02-17 10:46:55

标签: mysql

我需要一些帮助来搞清楚查询

我有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

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

有什么建议吗?

4 个答案:

答案 0 :(得分:1)

这应该按照您的要求进行,但如果没有样品输出,则很难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

这避免了必须进行潜在的昂贵操作,因为内部选择应该非常快并且可以根据需要进行限制

答案 1 :(得分:0)

这样做的典型方法是

  • 查找每个来源的MAX(time_added)
  • 为每个来源获取产品id
  • 加入sourcesorigin表以检索所有列

请注意,如果有多个记录的来源完全相同time_added,则此将失败

SQL声明

SELECT  *
FROM    sources s
        INNER JOIN origin o ON o.source_id = s.id
        INNER JOIN product p ON p.origin_id = o.id
        INNER JOIN (
          SELECT  id
          FROM    product p
                  INNER JOIN (
                    SELECT  origin_id
                            , MAX(time_added) AS time_addded
                    FROM    product p
                    GROUP BY
                            origin_id
                  ) pmax ON pmax.origin_id = p.origin_id
                            AND pmax.time_added = p.time_added                            
        ) pmax ON pmax.id = p.id                  

答案 2 :(得分:0)

SELECT o.id,count(o.id) as numOfProdFromOrig p.id, p.name, p.time_added, s.rank
FROM product as p NATURAL JOIN sources as s NATURAL JOIN origin as o
GROUP BY (numOfProdFromOrig)
ORDER BY s.rank DESC

答案 3 :(得分:0)

select b.id,(select p.name from  origin o inner join product p
on p.origin_id = o.id where o.source_id = b.id order by time_added desc limit 1)a as product_name
from source b ;

试试这个: