我有两张表如下:
表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
。
答案 0 :(得分:1)
如果你没有选择那个,你可以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
答案 1 :(得分:0)
为什么在UNION
两个表都可以使用JOIN
?
SELECT t1.Comment,
CASE WHEN t1.CommetDate > t2.CommentDate
THEN t1.commentDate
ELSE t2.commentDate
END AS commentDate
FROM t1 INNER JOIN t2 ON t1.RequestId = t2.RequestId
ORDER BY commentDate DESC
LIMIT 1