按子查询选择和排序查询

时间:2014-11-01 15:32:32

标签: mysql

我从table recipes中选择与idtable likes具有相同recipe_id并且具有特定user_id(1)的行。

我希望按照表格date中的likes排序/订购所有内容,而不是像我的示例中那样recipes ...

SELECT DISTINCT name, slugged_url 
FROM recipes
WHERE id 
IN
(
    SELECT recipe_id 
    FROM likes t
    LEFT JOIN users tn ON tn.id = t.user_id
    WHERE tn.id = '1'
)
AND publish = '1' 
ORDER BY date DESC
LIMIT 0 , 5

试图在次级查询中下订单,但没有工作。

1 个答案:

答案 0 :(得分:0)

您应该在外部查询中使用明确的join并使用group by代替distinct

SELECT r.name, r.slugged_url 
FROM recipes r JOIN
     likes l
     ON r.id = l.recipe_id
WHERE l.user_id = 1 AND r.publish = 1 
GROUP BY r.name, r.slugged_url 
ORDER BY MAX(l.date) DESC
LIMIT 0 , 5;

您不需要users表,因为您正在与id表中已有的likes进行比较。