[英]get records from two different tables based on their respective datetime fields - mysql
[英]sort rows based on fields from two different tables
我有兩個表,如下所示:
表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'
無法按順序排列。
嘗試選擇'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
可以同時JOIN
兩個表時為何使用UNION
?
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.