2011-11-05 64 views
0

是否有一種快速方法來確保您從MySQL JOIN查詢返回的記錄是唯一的?從mysql中保存返回的記錄是唯一的

下面的代碼可能會帶回兩次相同的類別。它的類別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 

回答

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/

1

如果我知道你需要什麼,你可以與關閉查詢:

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

這裏的問題是,你要加入單因此您將看到與「許多」表中的記錄一樣多的行。如果您只想爲每個類別帶回一行,則只需要查詢類別或決定要使用什麼條件從exp_category_posts中選擇單個值。

一個示例選項是查詢類別中最近的帖子,並加入該結果集而不是exp_category_posts。