我有一张这样的表:
CREATE TABLE `qanda` (
`id` int(11) UNSIGNED NOT NULL,
`subject` varchar(150) COLLATE utf8_unicode_ci NOT NULL,
`body` text COLLATE utf8_unicode_ci NOT NULL,
`body_html` text COLLATE utf8_unicode_ci NOT NULL,
`related` int(11) UNSIGNED DEFAULT NULL,
`type` tinyint(1) NOT NULL,
`amount` decimal(11,0) DEFAULT NULL,
`closed` tinyint(1) UNSIGNED DEFAULT NULL,
`CloserId` varchar(500) COLLATE utf8_unicode_ci NOT NULL,
`AcceptedAnswer` tinyint(1) DEFAULT NULL,
`aadate` int(11) UNSIGNED DEFAULT NULL,
`category` varchar(20) COLLATE utf8_unicode_ci NOT NULL,
`keywords` varchar(150) COLLATE utf8_unicode_ci NOT NULL,
`visibility` tinyint(1) NOT NULL,
`author_id` int(11) UNSIGNED DEFAULT NULL,
`editor_id` int(11) UNSIGNED DEFAULT NULL,
`date_time` int(11) UNSIGNED NOT NULL,
`edited_at` int(11) UNSIGNED DEFAULT NULL,
`activated_at` int(11) UNSIGNED DEFAULT NULL,
`activated_story` enum('سوال شده','ویرایش شده','جواب داده شده','') COLLATE utf8_unicode_ci NOT NULL,
`activator_id` int(11) UNSIGNED DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
此表存储问题和答案。这是我当前的查询,它提供了所有问题的列表,并根据投票对其进行排序:
SELECT *, (SELECT COALESCE(sum(vv.value),0)
FROM votes vv
WHERE qanda.id = vv.post_id) AS total_votes
FROM qanda
WHERE type = 0 -- "type=0" means questions
ORDER BY total_votes DESC
LIMIT :j,11;
现在我需要在WHERE
子句上再添加一个条件来排除有答案的问题。我想我需要self-join
。但我不知道如何在join
条款上写where
。有什么建议吗?
答案 0 :(得分:1)
使用NOT IN
排除已回答的ID:
SELECT *, (SELECT COALESCE(sum(vv.value),0)
FROM votes vv
WHERE qanda.id = vv.post_id) AS total_votes
FROM qanda
WHERE type = 0
AND id NOT IN (SELECT related FROM quanda WHERE type <> 0)
ORDER BY total_votes DESC
LIMIT :j,11;
答案 1 :(得分:1)
使用SELF JOIN
,您尝试将问题与任何答案匹配。如果找不到匹配项,您将获得NULL
,这样您就可以得到没有答案的问题。
SELECT questions.*
FROM qanda questions
LEFT JOIN qanda answers
ON question.id = answers.related
WHERE questions.type = 0
AND answers.id IS NULL