mysql选择多个子查询结果时:“子查询返回1行以上”

axr492tv  于 2021-06-15  发布在  Mysql
关注(0)|答案(1)|浏览(393)

我得到了一个“ Subquery returns more than 1 row “运行要返回两个子查询结果的查询时出错。为什么返回多行是这里的一个问题,我如何才能绕过这个问题?
数据表和相关字段如下所示: Accounts 身份证件 Meetings 帐户\u id
分配的用户id
开始日期 Users 身份证件

会议分配给帐户和用户。我正在尝试创建一个表,该表将显示会议开始日期在不同日期范围内的每个帐户的每个指定用户的会议数量。日期范围应排列在同一行中,作为带有以下标题的表格:
账户|用户名|未来1-31天会议|未来31-60天会议
如图所示:

.
我的问题是:

SELECT
(SELECT
    a.name
  FROM
    accounts AS a
  JOIN
    meetings AS m ON a.id = m.account_id
    AND date_start BETWEEN CURDATE() AND DATE_ADD(CURDATE(),INTERVAL 60 DAY)
  JOIN
    users AS u ON m.assigned_user_id = u.id
  WHERE
    m.status = 'Planned'
    AND m.deleted = 0
GROUP BY a.id, u.id) AS 'Account',
(SELECT
    u.last_name
  FROM
    accounts AS a
  JOIN
    meetings AS m ON a.id = m.account_id
    AND date_start BETWEEN CURDATE() AND DATE_ADD(CURDATE(),INTERVAL 60 DAY)
  JOIN
    users AS u ON m.assigned_user_id = u.id
WHERE
    m.status = 'Planned'
    AND m.deleted = 0
GROUP BY a.id, u.id) AS 'Name',
(SELECT
    COUNT(m.id)
  FROM
    accounts AS a
  JOIN
    meetings AS m ON a.id = m.account_id
    AND date_start BETWEEN CURDATE() AND DATE_ADD(CURDATE(),INTERVAL 30 DAY)
  JOIN
    users AS u ON m.assigned_user_id = u.id
  WHERE
    m.status = 'Planned'
    AND m.deleted = 0
GROUP BY a.id, u.id) AS 'Meetings 1-30 days',
(SELECT
    COUNT(m.id)
  FROM
    accounts AS a2
  JOIN
    meetings AS m ON a.id = m.account_id
    AND m.date_start BETWEEN DATE_ADD(CURDATE(),INTERVAL 31 DAY) AND DATE_ADD(CURDATE(),INTERVAL 60 DAY)
  JOIN
    users AS u ON m.assigned_user_id = u.id
  WHERE
    m.status = 'Planned'
    AND m.deleted = 0
GROUP BY a.id, u.id) AS 'Meetings 31-60 days'

包含帐户名和用户名的列必须作为子查询添加,以避免“ Operand should contain 1 column(s) “错误。与会议计数相对应的列必须是子查询,因为联接表的任何一行都不能同时适合这两个日期范围。每个子查询在单独运行时返回预期结果。但我明白了” Subquery returns more than 1 row “当子查询如图所示放在一起时。我试着给每个子查询分配不同的别名,但是没有用。

y0u0uwnf

y0u0uwnf1#

sql查询不返回嵌套的结果集;因此select子句中使用的表达式(如子查询)不能有多个值,因为这会“嵌套”它的值。您更可能只需要使用条件聚合,如下所示:

SELECT a.id, u.id, a.name, u.last_name
    , COUNT(CASE WHEN m.date_start BETWEEN CURDATE() AND DATE_ADD(CURDATE(),INTERVAL 30 DAY) THEN 1 ELSE NULL END) AS `Meetings 1-30 days`
    , COUNT(CASE WHEN m.date_start BETWEEN DATE_ADD(CURDATE(),INTERVAL 31 DAY) AND DATE_ADD(CURDATE(),INTERVAL 60 DAY) THEN 1 ELSE NULL END) AS `Meetings 31-60 days`
    , COUNT(CASE WHEN  THEN 1 ELSE NULL END) AS 
FROM accounts AS a
JOIN meetings AS m ON a.id = m.account_id
JOIN users AS u ON m.assigned_user_id = u.id
WHERE m.status = 'Planned' AND m.deleted = 0
  AND m.date_start BETWEEN CURDATE() AND DATE_ADD(CURDATE(),INTERVAL 60 DAY)
GROUP BY a.id, u.id, a.name, u.last_name
;

注意:else null在技术上是自动的,可以省略;只是为了清楚起见。聚合函数,如count,忽略空值;空值影响这些函数的唯一时间是当它们只遇到空值时(在这种情况下,它们的结果是空的)。
旁注:您可以继续以类似于原来的形式进行查询;如果在子查询的结果中包含分组字段,则子查询可能已经连接在一起(但这会导致大量帐户、会议和用户的冗余连接)。

相关问题