选择两列不同表之间的差异/减号

时间:2016-06-06 14:36:30

标签: php mysql sql join pdo

我正在尝试计算消息是否被看到/看不见,是否已读/未读。

data_chats_parties表格中,有两个字段last_seenlast_read

data_chats_messages表中,有一个字段created表示消息的创建时间。

我需要从last_seen中的时间戳中减去last_readcreated的时间戳。

在对同一个表的列执行数学运算时,查询工作正常,但是当我使用不同的表时,它会返回一个空结果。

这是我现有的查询:

  SELECT
        data_chats.id AS chat,
        data_chats_parties.*,
       (SELECT COUNT(data_chats_parties.id) FROM data_chats_parties
        WHERE data_chats_parties.chat = data_chats.id) AS total_parties,
        data_chats_messages.created AS last_message_created,
        data_chats_messages.author AS last_message_author,
        data_chats_messages.author_type AS last_message_author_type,
        data_chats_messages.message AS last_message,

        (data_chats_messages.created - data_chats_parties.last_seen) AS unseen,
        (data_chats_messages.created - data_chats_parties.last_read) AS unread

      FROM data_chats
        INNER JOIN data_chats_parties ON data_chats_parties.chat=data_chats.id
        LEFT JOIN data_chats_messages ON data_chats_messages.chat=data_chats.id AND data_chats_messages.active=1
      WHERE
        data_chats.active=1 AND
        data_chats_parties.member=1 AND
        data_chats_parties.status >= 1
      GROUP BY data_chats_parties.chat
      ORDER BY last_message_created DESC

假设此查询按计划运行,如果unreadunseen> 0,则该查询无法看到或未读。

理想情况下,我可以将unreadunseen设置为10而不是更改值,以便排序更容易,但如果不是可能我的原始方法就足够了。

1 个答案:

答案 0 :(得分:1)

尝试使用IF,如下所示:

SELECT
    data_chats.id AS chat,
    data_chats_parties.*,
   (SELECT COUNT(data_chats_parties.id) FROM data_chats_parties
    WHERE data_chats_parties.chat = data_chats.id) AS total_parties,
    data_chats_messages.created AS last_message_created,
    data_chats_messages.author AS last_message_author,
    data_chats_messages.author_type AS last_message_author_type,
    data_chats_messages.message AS last_message,

    IF(data_chats_messages.created > data_chats_parties.last_seen,1,0) AS unseen,
    IF(data_chats_messages.created > data_chats_parties.last_read,1,0) AS unread

  FROM data_chats
    INNER JOIN data_chats_parties ON data_chats_parties.chat=data_chats.id
    LEFT JOIN data_chats_messages ON data_chats_messages.chat=data_chats.id AND data_chats_messages.active=1
  WHERE
    data_chats.active=1 AND
    data_chats_parties.member=1 AND
    data_chats_parties.status >= 1
  GROUP BY data_chats_parties.chat
  ORDER BY last_message_created DESC