WHERE子查询= 0

时间:2014-07-08 15:56:43

标签: mysql sql

我正在尝试编写一个查询,检查问题是否有任何被标记为正确答案的答案。

现在我尝试使用子查询,并尝试将子查询设置为用户定义的变量。

测试#1

SELECT
    @id := `id` AS `id`, `title`
FROM
    `eu_questions`
WHERE
    CAST((SELECT COUNT(`id`) FROM `eu_answers` WHERE `question_id` = @id AND `correct` = 1) AS UNSIGNED) = 0
ORDER BY `id` ASC
LIMIT 0, 10;

测试#2

SELECT
    @id := `id` AS `id`,
    @count_correct := (SELECT COUNT(`id`) FROM `eu_answers` WHERE `question_id` = @id AND `correct` = 1) AS `count_correct`
FROM
    `eu_questions`
WHERE
    CAST(@count_correct AS UNSIGNED) = 0
ORDER BY `id` ASC
LIMIT 0, 10;

查询不会导致错误,它们只返回0结果,我不明白为什么?我尝试在选择时比较用户定义的变量,这似乎可以工作并返回正确的值,这样只会让我更加烦恼!

这就是我检查的方式:

SELECT
    @id := `id` AS `id`,
    @count_correct := (SELECT COUNT(`id`) FROM `eu_answers` WHERE `question_id` = @id AND `correct` = 1) AS `count_correct`,
    CAST(@count_correct AS UNSIGNED) = 0
FROM
    `eu_questions`
ORDER BY `id` ASC
LIMIT 0, 10;

答案 - 感谢Branko Dimitrijevic

我使用了他的例子并最终得到了符合我需要的查询。

SELECT *
FROM `eu_questions`
WHERE
    1 != ANY (
        SELECT COUNT(`id`)
        FROM `eu_answers`
        WHERE `question_id` = `eu_questions`.`id`
        AND `correct` = 1
    )
ORDER BY `id` ASC
LIMIT 0, 10;

2 个答案:

答案 0 :(得分:1)

你走了:

SELECT *
FROM eu_questions
WHERE 1 = ANY (
  SELECT correct
  FROM eu_answers
  WHERE question_id = eu_questions.id
);

[SQL Fiddle]

根据需要添加额外的WHERE和LIMIT条件......

答案 1 :(得分:0)

您可以在答案表上LEFT JOIN并使用where子句仅保留没有正确答案的问题。

SELECT
    `eu_questions`.`id`, `title`
FROM
    `eu_questions`
LEFT JOIN
    `eu_answers` ON `question_id` = `eu_questions`.`id` AND `correct` = 1
WHERE 
    `eu_questions`.`id` IS NULL
ORDER BY `eu_questions`.`id` ASC
LIMIT 0, 10;