MySQL查询,尽管不匹配HAVING语句但返回结果

时间:2014-05-04 18:04:59

标签: mysql sql

我有这个查询(很少运行所以效率低下)

SELECT
  FileId as Id,
  1 as IsFile,
  0 as IsDir,
  Backend as MajorType,
  SpecificId as MinorType,
  Flags,
  Name,
  Folder as InFolder,
  Created,
  Modified
FROM FileSystem_Files

UNION

SELECT
  FolderId as Id,
  0 as IsFile,
  1 as IsDir,
  `Type` as MajorType,
  0 as MinorType,
  Flags,
  Name,
  ParentFolder as InFolder,
  Created,
  Modified
FROM FileSystem_Folders

HAVING InFolder=2;

然后我回来了,“InFolder”实际上是1.尽管有。

所以我猜这是因为有部分只是应用于联合的第二部分,我该如何重新定义查询? (这将是一个视图,当它完成,但在那之前......)

3 个答案:

答案 0 :(得分:0)

SELECT * FROM (
  SELECT
    FileId as Id,
    1 as IsFile,
    0 as IsDir,
    Backend as MajorType,
    SpecificId as MinorType,
    Flags,
    Name,
    Folder as InFolder,
    Created,
    Modified
  FROM FileSystem_Files

  UNION ALL

  SELECT
    FolderId as Id,
    0 as IsFile,
    1 as IsDir,
    `Type` as MajorType,
    0 as MinorType,
    Flags,
    Name,
    ParentFolder as InFolder,
    Created,
    Modified
  FROM FileSystem_Folders
) AS t
WHERE t.InFolder=2;

请注意,HAVINGWHERE不同。 WHERE用于行的条件,而HAVING用于组的条件。

答案 1 :(得分:0)

您不需要使用HAVING,因为您的查询中没有GROUP BY子句。 带有WHERE子句的简单嵌套查询将满足您的需求 -

SELECT * FROM 
(SELECT
  FileId as Id,
  1 as IsFile,
  0 as IsDir,
  Backend as MajorType,
  SpecificId as MinorType,
  Flags,
  Name,
  Folder as InFolder,
  Created,
  Modified
FROM FileSystem_Files

UNION

SELECT
  FolderId as Id,
  0 as IsFile,
  1 as IsDir,
  `Type` as MajorType,
  0 as MinorType,
  Flags,
  Name,
  ParentFolder as InFolder,
  Created,
  Modified
FROM FileSystem_Folders) COMBINED_VIEW
WHERE COMBINED_VIEW.InFolder=2;

答案 2 :(得分:-1)

这可行吗?

SELECT
  FileId as Id,
  1 as IsFile,
  0 as IsDir,
  Backend as MajorType,
  SpecificId as MinorType,
  Flags,
  Name,
  Folder as InFolder,
  Created,
  Modified
FROM FileSystem_Files
WHERE InFolder=2

UNION

SELECT
  FolderId as Id,
  0 as IsFile,
  1 as IsDir,
  `Type` as MajorType,
  0 as MinorType,
  Flags,
  Name,
  ParentFolder as InFolder,
  Created,
  Modified
FROM FileSystem_Folders
WHERE InFolder=2