使用mysql与union all的问题

时间:2015-10-09 18:59:25

标签: mysql

 select `C1`.`ID` AS `ID`,
`C1`.`Article_ID` AS `Article_ID`,
`C1`.`DateAdded` AS `DateAdded`,
`C1`.`Votes` AS `Votes`,
`C1`.`Content` AS `Content`,
(select 0) AS `isReply`,
`C1`.`Usr_ID` AS `Usr_ID`,
(select NULL) AS `RepliedTo` 
from `Comment` as C1
where isnull(`C1`.`Reply_ID`) limit 5
UNION ALL
select 
`C2`.`Reply_ID` AS `Reply_ID`,
`C2`.`Article_ID` AS `Article_ID`,
`C2`.`DateAdded` AS `DateAdded`,
`C2`.`Votes` AS `Votes`,
`C2`.`Content` AS `Content`,
`C2`.`ID` AS `isReply`,
`C2`.`Usr_ID` AS `Usr_ID`,
`C2`.`RepliedTo` AS `RepliedTo` 
from `Comment` as C2
where (`C2`.`Reply_ID` = `C1`.`Reply_ID` )

我的问题位于where (C2.Reply_ID = C1.Reply_ID )

的最后一行C2.Reply_ID=C1.Reply_ID

Unknown column C1.Reply_ID in where clause出现错误。

我的目标是我想要检索

Table1的所有行

全联盟

Table2的行使用从where子句

中的Table1检索的ID

2 个答案:

答案 0 :(得分:1)

您无法使用第二个选择中第一个选择的表格。

您必须在第二个选择查询中重复第一个查询

select `C1`.`ID` AS `ID`,
`C1`.`Article_ID` AS `Article_ID`,
`C1`.`DateAdded` AS `DateAdded`,
`C1`.`Votes` AS `Votes`,
`C1`.`Content` AS `Content`,
(select 0) AS `isReply`,
`C1`.`Usr_ID` AS `Usr_ID`,
(select NULL) AS `RepliedTo` 
from `Comment` as C1
where isnull(`C1`.`Reply_ID`) limit 5
UNION ALL
select 
`C2`.`Reply_ID` AS `Reply_ID`,
`C2`.`Article_ID` AS `Article_ID`,
`C2`.`DateAdded` AS `DateAdded`,
`C2`.`Votes` AS `Votes`,
`C2`.`Content` AS `Content`,
`C2`.`ID` AS `isReply`,
`C2`.`Usr_ID` AS `Usr_ID`,
`C2`.`RepliedTo` AS `RepliedTo` 
from `Comment` as C2
where (`C2`.`Reply_ID` in (select `C1`.`ID` 
from `Comment` as C1
where isnull(`C1`.`Reply_ID`) limit 5)

答案 1 :(得分:1)

这应该让你接近你想要的东西:

SELECT `ID` AS `ID`
   , `Article_ID` AS `Article_ID`
   , `DateAdded` AS `DateAdded`
   , `Votes` AS `Votes`
   , `Content` AS `Content`
   , IF(copyTbl.copyNum=1, 0, `ID`) AS `isReply`
   , `Usr_ID` AS `Usr_ID`
   , IF(copyTbl.copyNum=1, NULL, `RepliedTo`) AS `RepliedTo` 
FROM `Comment`, (SELECT 1 AS copyNum UNION SELECT 2) AS copyTbl
WHERE `Reply_ID` IS NULL
ORDER BY `ID`, copyTbl.copyNum
LIMIT 10
;

它假定CommentID是唯一的;如果不是这种情况,则需要相应地调整ORDER BY