在单个查询中具有多个选定结果的多个select语句

时间:2017-03-08 14:36:00

标签: mysql sql

我正在尝试将多个选项链接到一个查询中我已经查看了这里的另一个线程,这有很大帮助,但这只考虑了单选项,如此。

  SELECT  (
    SELECT COUNT(*)
    FROM   user_table
    ) AS tot_user,
    (
    SELECT COUNT(*)
    FROM   cat_table
    ) AS tot_cat,
    (
    SELECT COUNT(*)
    FROM   course_table
    ) AS tot_course

但我的问题是我试图从每个选择中获得多个选项。

SELECT (
SELECT c.name AS Company,
CONCAT(UPPER(u.forename),' ', u.surname) AS Username,
count(c.case) AS 'No. of Private Cases Generated',
) AS 'No. of Private Cases Generated',
(
SELECT c.name AS Company,
CONCAT(UPPER(u.forename),' ', u.surname) AS Username,
count(c.case) AS 'No. of Web Cases Generated'
) AS 'No. of Web Cases Generated'

我一直收到错误"#1241 - 操作数应包含1列"

从我读到的这是因为我试图在一个选择器下链接3个不同的值,我不想这样做。

最后这段代码就是问题所在。

) AS 'No. of Web Cases Generated'

我试过这个问题来解决,但很明显我错过了正确的专业知识。

) "" AS Company,
  "" AS Username,
  "" AS 'No. of Private Cases Generated',
  AS 'No. of Web Cases Generated'

这不起作用,因为它不知道分配给什么选择器的值。

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

是的,这是正确的行为,因为您实际上是在尝试在单列中合并多个列值,这是不可能的

( SELECT c.name AS Company,
CONCAT(UPPER(u.forename),' ', u.surname) AS Username,
count(c.case) AS 'No. of Private Cases Generated',
) AS 'No. of Private Cases Generated',

认为您要找的是UNION,而不是

SELECT c.name AS Company,
CONCAT(UPPER(u.forename),' ', u.surname) AS Username,
count(c.case) AS 'No. of Private Cases Generated'
FROM some_table  --first part of query

UNION            -- combine the data

SELECT c.name AS Company,
CONCAT(UPPER(u.forename),' ', u.surname) AS Username,
count(c.case) AS 'No. of Web Cases Generated'
FROM some_other_table;  -- second part of query

根据您的评论,执行JOIN然后

select xx.Company, xx.Username,xx.'No. of Private Cases Generated',
xxx.Company1, xxx.Username1, xxx.'No. of Web Cases Generated'
FROM (
SELECT c.name AS Company,
CONCAT(UPPER(u.forename),' ', u.surname) AS Username,
count(c.case) AS 'No. of Private Cases Generated',
FROM some_table  ) xx

JOIN (
SELECT c.name AS Company,
CONCAT(UPPER(u.forename),' ', u.surname) AS Username,
count(c.case) AS 'No. of Web Cases Generated'
FROM some_other_table ) xxx
ON xx.Company = xxx.Company;