MySQL语法错误,关于union和关键字

时间:2017-10-02 04:24:45

标签: mysql sql

select distinct id, item from 
(
    (
        (
            select ID as id, "INNER" as item 
            from TREE 
            where ID in 
            (
                select P_ID from TREE as T1
            )  
            and P_ID is not null
        ) 
        as T3
    )
    union
    (
        (
            select ID as id, "ROOT" as item 
            from TREE 
            where P_ID IS NULL
        ) 
        as T2
    )
)

TREE表的结构如下:

ID, P_ID
1,2
3,4
5,6

我是SQL中的菜鸟,我真的不知道为什么执行它时总会出现问题。

  

错误代码:1064。您的SQL语法有错误;检查   手册,对应右边的MySQL服务器版本   在第22行使用'as T2)附近的语法

你可以告诉我吗?谢谢!

1 个答案:

答案 0 :(得分:3)

不知道您要从查询中实现的目标,但修复了可以重写查询的语法错误

SELECT DISTINCT 
  id,
  item 
FROM(
  SELECT 
    ID AS id,
    "INNER" AS item 
  FROM
    TREE 
  WHERE ID IN (SELECT P_ID FROM TREE) 
  AND P_ID IS NOT NULL 

  UNION

  SELECT 
    ID AS id,
    "ROOT" AS item 
  FROM
    TREE 
  WHERE P_ID IS NULL
) as t