从不相关的SQL子查询中返回多行

时间:2017-08-25 07:56:15

标签: mysql sql

我正在编写一个SQL脚本来检查MySQL数据库的完整性。查询检查不同表的不同方面,因此它们不相关。我不想把它们联系起来。我只想一个接一个地看到不同查询的结果。

单个查询工作正常,但我想同时运行它们,但保持结果分开。它们可以不返回任何内容,也可以返回多行。 (理想情况下,我喜欢标题以使结果更清晰。)

错误是

  

"错误代码:1242。子查询返回超过1行"

以下是我尝试的内容:

SELECT
(-- Teams not associated with any employees
SELECT id 
  FROM teams
 WHERE NOT EXISTS
          (SELECT id 
             FROM employee_teams
            WHERE employee_teams.teamID IN(teams.id))) AS TeamNoEmployee,

(-- Teams deleted but associated with employees
SELECT teamID 
  FROM employee_teams
 WHERE NOT EXISTS
          (SELECT id 
             FROM teams
            WHERE teams.id IN(employee_teams.teamID))) AS TeamsDeleted

更新:@JohnHC得到了它。这是我的新版本。我需要能够为每个查询添加一个标题,这样我才能区分它们。

-- Teams not associated with any employees
SELECT 'Team No Employee' AS Test, id
  FROM teams
 WHERE NOT EXISTS
          (SELECT id 
             FROM employee_teams
            WHERE employee_teams.teamID IN(teams.id))
UNION
-- Teams deleted but associated with employees
SELECT 'Teams Deleted', teamID 
  FROM employee_teams
 WHERE NOT EXISTS
          (SELECT id 
             FROM teams
            WHERE teams.id IN(employee_teams.teamID))

1 个答案:

答案 0 :(得分:3)

你并没有真正把桌子上的那些联系起来。反过来尝试一下,像这样:

select 'Empty Team' as Scenario, id
from teams t1
left join employee_teams et
  on et.teamID = t1.id
where et.id is null
union 
select 'Deleted Team', teamid
from employee_teams et
left join teams t2
  on t2.id = et.teamID
where t2.id is null