保持mysql返回的记录唯一

时间:2011-11-05 15:00:16

标签: mysql left-join

是否有一种快速方法可以确保从MySQL JOIN查询返回的记录是唯一的?

以下代码可能会两次带回同一类别。它的类别ID应该是不同的!

SELECT 
   exp_categories.cat_name, exp_categories.cat_id, exp_categories.cat_url_title
  ,exp_category_posts.entry_id, exp_channel_titles.status 
FROM (exp_categories 
LEFT JOIN exp_category_posts 
       ON exp_categories.cat_id = exp_category_posts.cat_id) 
LEFT JOIN exp_channel_titles 
       ON exp_category_posts.entry_id = exp_channel_titles.entry_id 
WHERE exp_categories.group_id = 2 
  AND exp_category_posts.entry_id IS NOT NULL 
  AND exp_channel_titles.status = 'open' 
ORDER BY RAND() 
LIMIT 2

3 个答案:

答案 0 :(得分:1)

如果我了解您的需求,您可以通过以下方式关闭查询:

GROUP BY exp_categories.cat_id
ORDER BY RAND() 
LIMIT 2

答案 1 :(得分:1)

这里的问题是你加入了一对多,所以你会看到与“many”表中的记录一样多的行。如果您只想为每个类别返回一行,则需要仅查询类别或决定要使用哪些条件从exp_category_posts中选择单个值。

一个示例选项是查询类别中的最新帖子并加入该结果集而不是exp_category_posts。

答案 2 :(得分:0)

    SELECT 
   exp_categories.cat_name, exp_categories.cat_id, exp_categories.cat_url_title
  ,exp_category_posts.entry_id, exp_channel_titles.status 
FROM (exp_categories 
LEFT JOIN exp_category_posts 
       ON exp_categories.cat_id = exp_category_posts.cat_id) 
LEFT JOIN exp_channel_titles 
       ON exp_category_posts.entry_id = exp_channel_titles.entry_id 
WHERE exp_categories.group_id = 2 
  AND exp_category_posts.entry_id IS NOT NULL 
  AND exp_channel_titles.status = 'open' 
  GROUP BY exp_categories.cat_id
ORDER BY RAND() 
LIMIT 2

编辑:在GROUP BY子句中添加要区分的列将确保只返回1。此外,强烈建议不要使用ORDER BY RAND(),请参阅:http://www.titov.net/2005/09/21/do-not-use-order-by-rand-or-how-to-get-random-rows-from-table/

相关问题