MYSQL视图未按预期排序

时间:2013-09-18 01:39:52

标签: mysql sql

我有一张鸡尾酒配方和其他东西的表。我有另一张表,显示了喜欢的食谱。我想在最后一天查看上面提到的食谱,如果结果是< 1000,请用随机食谱填写剩余的1000,而不是FEED表。

实施例

Feed :食谱1今天(1分钟前)(鸡尾酒),食谱2昨天喜欢(不是鸡尾酒),今天喜欢的食谱3(1小时前)(鸡尾酒),食谱4赞了今天(3分钟前)(不是鸡尾酒会)。

食谱表: 自我解释

类别表:

recipe 1, cocktail
recipe 2, juice
recipe 3, cocktail
recipe 4 juice
recipe 3333 cocktail
recipe 4444 cocktail
recipe nnnn cocktail

我的查看需要显示:

食谱1,食谱4,食谱3(最近订购时喜欢)。然后填写1000的其余部分,从食谱表中随机获取:食谱4444,食谱3333,食谱nnnn。

最终结果:食谱1,食谱4,食谱3,食谱4444,食谱3333,食谱nnnn

下面的代码尝试这样做,但顺序错误(顶部没有按顺序排列配方1,4,3。它们混合在一起......

CREATE 
    ALGORITHM = UNDEFINED 
    DEFINER = `XXXX` 
    SQL XXXX
VIEW `cocktails` AS
    (select 
        `r`.`name` AS `name`,
        `r`.`myId` AS `myId`
    from
        ((`recipe` `r`
        join `feed` `f` ON ((`r`.`myId` = `f`.`recipe_id`)))
        join `category` `c` ON ((`r`.`myId` = `c`.`recipe_id`)))
    where
        (`c`.`name` like '%cocktails%')
    group by `r`.`name`
    order by (max(`f`.`timeStamp`) >= (now() - interval 1 day)) desc , (`r`.`myId` is not null) desc)

    union 

    (select 
        `r`.`name` AS `name`,
        `r`.`myId` AS `myId`
    from
        ((`recipe` `r`
        join `category` `c` ON (`r`.`myId` = `c`.`recipe_id`)))
    where
        (`c`.`name` like '%cocktails%')

    )
    limit 0,1000

1 个答案:

答案 0 :(得分:1)

我认为你可以在MySQL的视图中使用order by。但是,我认为您可以通过组合查询来解决您的问题。对left outer join表执行feeds。然后,根据Feed的存在对结果进行排序:

CREATE VIEW cocktails AS
    select r.name, r.myId
    from recipe r join
         category c
         ON r.myId = c.recipe_id left outer join
         feed f
         ON r.myId = f.recipe_id
    where c.name like '%cocktails%'
    group by r.name
    order by (f.recipe_id is not null) desc,
             max(f.timestamp) >= (now() - interval 1 day) desc,
             r.myId is not null desc
    limit 0,1000;

我也摆脱了后面的引号 - 它们使代码很难阅读。