【问题标题】:sort rows based on fields from two different tables根据来自两个不同表的字段对行进行排序
【发布时间】:2015-05-10 23:26:21
【问题描述】:

我有两张表如下:

表 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。

【问题讨论】:

  • 嗯,所以也许您需要限定列名。你能显示你的桌子的布局信息吗?
  • t1-RequestId, Raised_By,CommentDate,Comment,AttachmentName,Attachment,AttachmentSize t2-RequestId, CommentDate,Comment,RaisedBy

标签: php mysql mysqli mysql-workbench


【解决方案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

【讨论】:

    【解决方案2】:

    既然可以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
    

    【讨论】:

    • 只有在两个表中始终存在与指定的RequestID 匹配的记录时才使用INNER JOIN。此外,您必须针对最新的评论日期返回正确的评论,而不是总是返回 t1.Comment。
    • @MarcusAdams 我将 OP 解释为两个表中总是有项目(因为他/她说“谁的 RequestID=RequestID”)。至于正确的评论,我需要另一个 CASE 还是有更好的方法?
    猜你喜欢
    • 2023-02-02
    • 1970-01-01
    • 2016-10-12
    • 1970-01-01
    • 2019-03-04
    • 1970-01-01
    • 2020-05-14
    • 1970-01-01
    • 2021-05-16
    相关资源
    最近更新 更多