我有一个邮件列,我正在试图弄清楚我应该如何在"发送"文件夹中。
我运行以下查询:
SELECT
`text`,
`created`
FROM
`messages`
WHERE
`status` = 1
ORDER BY `created` DESC
LIMIT 1
我想引入一个条件,以便只有当status = 1
的最后一行也有user_from = $user
时返回结果(如果最后一行有user_to = $user
,则不应该返回任何内容)
我的查询应该是什么?
答案 0 :(得分:2)
您可以使用subquery
select `text`, `created` from T1
( SELECT
`text`,
`created`
FROM
`messages`
WHERE
`status` = 1
ORDER BY `created` DESC
LIMIT 1) T1
where `user_from` = $user and `user_to` != $user
答案 1 :(得分:0)
如果我理解你的问题,你想这样做吗?
SELECT
`text`,
`created`
FROM
`messages`
WHERE
`status` = 1
AND `user_from` = $user
AND `user_to` != $user
ORDER BY `created` DESC
LIMIT 1
当然,您需要将$user
替换为您的字符串,或使用预准备语句将变量插入查询中。
答案 2 :(得分:0)
选择status = 1的最新消息,然后将其用作嵌套查询并检查条件以输出这一行结果:
select `text`, `created`
from
(
SELECT
`text`,
`created`,
user_from,
user_to
FROM
`messages`
WHERE
`status` = 1
ORDER BY `created` DESC
LIMIT 1
) t
where (user_from = $user)
and (not (user_to = $user))