我有两个表,如下所示:
表1(t1)
______________________________________________________________________________________________
RequestId | Raised_By | CommentDate | Comment | AttachmentName | Attachment | AttachmentSize |
----------+-----------+-------------+---------+----------------+------------+----------------+
表2(t2)
______________________________________________
RequestId | CommentDate | Comment | Raised_By |
----------+-------------+---------+-----------+
注意:
CommentDate
是timestamp
我想选择唯一的一条记录,即从表
t1
或t2
中注释,它们的RequestId=RequestId
和CommentDate
是最新的。我的查询如下:
(SELECT Comment from t1 WHERE RequestId = "."\"".$_POST['RequestId']."\" and Raised_By="."\"".$_POST['Raised_By']."\" and CommentDate="."\"".$_POST['CommentDate']."\")
UNION
(SELECT Comment from t2 WHERE RequestId = "."\"".$_POST['RequestId']."\" and Raised_By="."\"".$_POST['Raised_By']."\" )
ORDER BY CommentDate DESC
LIMIT 1
但是我说
unknown column CommentDate
时出错。 最佳答案
如果尚未选择,可以ORDER BY
吗?
我们需要了解查询执行的顺序。除非您选择字段'CommentDate'
,否则您无法按顺序排列。
尝试选择'CommentDate'
和'Comment'
并检查
(SELECT Comment, CommentDate from t1 WHERE RequestId = "."\"".$_POST['RequestId']."\" and Raised_By="."\"".$_POST['Raised_By']."\" and CommentDate="."\"".$_POST['CommentDate']."\")
UNION
(SELECT Comment, CommentDate from t2 WHERE RequestId = "."\"".$_POST['RequestId']."\" and Raised_By="."\"".$_POST['Raised_By']."\" )
ORDER BY CommentDate DESC
LIMIT 1