在SELECT期间,确定另一个表中的相关行数(0-n)

时间:2013-02-02 17:33:31

标签: mysql sql

** 修改 **

我使用了第一个答案中的查询,但最终不得不修改它,因为它不会返回多个没有任何会话的调查。我终于解决了这个问题:

(SELECT i.id AS id, i.title AS title, c.title AS ctitle, c.color AS ccolor,
                     i.active AS active, i.length AS length, i.redirect AS redirect,
                     COUNT(s.sid) AS number
                FROM survey_info i
                LEFT JOIN survey_sessions s ON s.sid = i.id
                INNER JOIN survey_category c ON i.category = c.id
                WHERE s.sid IS NOT NULL
                GROUP BY s.sid)
                UNION ALL
                (SELECT i.id AS id, i.title AS title, c.title AS ctitle, c.color AS ccolor,
                       i.active AS active, i.length AS length, i.redirect AS redirect,
                       0 AS number
                FROM survey_info i
                LEFT JOIN survey_sessions s ON s.sid = i.id
                INNER JOIN survey_category c ON i.category = c.id
                WHERE s.sid IS NULL)
                ORDER BY 2

要解释一下,从下面进行查询,只返回有会话(已经采取)的调查,然后使用UNION ALL子句将这些结果与仅检索没有调查的SELECT相结合会议(尚未采取。)最后,它按第二列(调查标题)对合并结果进行排序

我希望这可以帮助其他人。

-------------------------------------------- ------------------------------------------------

我一直致力于一项让人们创建和管理调查的调查计划。昨天我问了一个关于存储结果的问题,并意识到我做错了(为每个调查创建额外的表颤抖

我现在有了一个新的表结构,效果更好,并且始终保持在6个表中。 我有一个新的困境,我整夜都在工作,希望有人能指出我正确的方向。

我的表现在如下:

survey_info

id(bigint)        PK
title(varchar)
category(bigint)
length(bigint)
active(tinyint)

survey_category

id(bigint)        PK
title(varchar)
color(varchar)

survey_sessions

id                PK
timestamp(bigint)

我最初使用以下SQL收集调查及其会话数(所用时间)

SELECT i.id AS id, i.title AS title, c.title AS ctitle, c.color AS ccolor,
       i.active AS active, i.length AS length, i.redirect AS redirect,
       COUNT(s.sid) AS number
FROM survey_info i, survey_category c, survey_sessions s
WHERE i.category = c.id AND s.sid = i.id
GROUP BY s.sid

但是,正如您可能已经猜到的,这意味着每当我创建一个新的调查(从未采取过)时,它都不会显示在此列表中,因为survey_session表中没有条目。< / p>

当survey_sessions中没有行时,是否可以使用MySQL中的条件语句返回0代替“COUNT(s.sid)AS号”?我已经阅读了很多关于LEFT JOIN的内容,但我认为它们不会起作用,因为没有任何东西可以将新调查连接到survey_sessions表。

1 个答案:

答案 0 :(得分:2)

以下是您的查询已重写为LEFT JOINsurvey_sessions。如果适合您,您应该能够轻松检查。

SELECT i.id AS id, i.title AS title, c.title AS ctitle, c.color AS ccolor,
    i.active AS active, i.length AS length, i.redirect AS redirect,
    COUNT(s.sid) AS number
FROM survey_info i
INNER JOIN survey_category c ON i.category = c.id
LEFT JOIN survey_sessions s ON s.sid = i.id
GROUP BY s.sid