根据两个不同表中的字段对行进行排序

时间:2015-03-09 17:31:28

标签: php mysql mysqli mysql-workbench

我有两张表如下:

表1(t1)

______________________________________________________________________________________________
RequestId | Raised_By | CommentDate | Comment | AttachmentName | Attachment | AttachmentSize |
----------+-----------+-------------+---------+----------------+------------+----------------+

表2(t2)

______________________________________________
RequestId | CommentDate | Comment | Raised_By |
----------+-------------+---------+-----------+

注意:CommentDatetimestamp

我想选择唯一一条记录,即表格t1t2的评论,其中RequestId=RequestIdCommentDate是最新的。

我的查询如下:

(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

2 个答案:

答案 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