2015-06-02 33 views
4

我有一個照片競賽應用程序,用戶可以投票。我想選擇登錄用戶尚未投票的所有比賽。MySQL選擇用戶尚未投票的行(比賽應用程序)

所以我有兩個表。

的 「較量」 表:

CREATE TABLE `contest` (
    `id` int(11) NOT NULL AUTO_INCREMENT, 
    `user_id` int(11) NOT NULL, 
    `category_id` int(11) NOT NULL, 
    `title` varchar(255) NOT NULL, 
    `desc` text NOT NULL, 
    `created_date` datetime NOT NULL, 
    `started_date` datetime NOT NULL, 
    `nb_user_min` int(11) NOT NULL, 
    `nb_photo_max` int(11) NOT NULL, 
    `nb_photo_per_user` int(11) NOT NULL, 
    `duration` int(11) DEFAULT NULL, 
    `status` int(11) NOT NULL, 
    PRIMARY KEY (`id`) 
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; 

的 「contest_vote」 表:

CREATE TABLE `contest_vote` (
    `id` int(11) unsigned NOT NULL AUTO_INCREMENT, 
    `pic_id` int(11) DEFAULT NULL, 
    `contest_id` int(11) DEFAULT NULL, 
    `user_id` int(11) DEFAULT NULL, 
    `date` datetime DEFAULT NULL, 
    `ip` varchar(100) DEFAULT NULL, 
    PRIMARY KEY (`id`) 
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; 

所以要明確,我想要得到的數目(或清單)用戶尚未投票的比賽。所以我嘗試了一個LEFT JOIN,但它沒有返回一組好的結果。這裏它是我到目前爲止的查詢:

SELECT DISTINCT c.id, c.title, cv.user_id 
FROM contest c 
LEFT JOIN contest_vote cv 
ON cv.contest_id = c.id AND cv.user_id != ? 
GROUP BY contest_id 

(「?」代表user_id參數)。

你能幫我解決嗎?

回答

2

這對於子查詢來說很簡單。只要抓住其中沒有用戶投票所有類似的比賽:

SELECT DISTINCT c.id, c.title 
FROM contest c 
WHERE c.id NOT IN (SELECT DISTINCT cv.contest_id FROM contest_vote cv WHERE cv.user_id = ?) 
+0

我需要的!非常感謝你! – fraxool

0

試試這個:

SELECT DISTINCT c.id, c.title, cv.user_id 
FROM contest c 
LEFT JOIN contest_vote cv ON cv.contest_id = c.id AND cv.user_id != ? WHERE c.user_id = ? 
GROUP BY contest_id 
相關問題