任何人都不知道如何选择它。 表消息如下所示:
+----+------------+----------+---------+--------+-------------------+
| id | fromUserID | toUserID | message | status | dt |
+----+------------+----------+---------+--------+-------------------+
| 1 | 1 | 2 |Hey,wh...| seen |2018-08-15 17:43:51|
| 2 | 2 | 1 | Hey | send |2018-08-15 17:45:51|
+----+------------+----------+---------+--------+-------------------+
我要使用MySql查询:
SELECT m.id,
(SELECT m.message, IF(m.fromUserID='1',1,0), m.status, m.dt
FROM messages m
WHERE (m.fromUserID='1' OR m.toUserID='1') AND (m.fromUserID=u.id OR m.toUserID=u.id)
ORDER BY m.dt DESC
LIMIT 1) AS m,
u.username,
u.id AS usID
FROM messages m
JOIN users u
ON u.id=IF(m.fromUserID='1',m.toUserID,m.fromUserID)
WHERE (m.fromUserID='1' OR m.toUserID='1') AND
m.dt>IFNULL((SELECT d.dt FROM deletechat d WHERE d.userID='1' AND d.withUserID=IF(m.fromUserID='1',m.toUserID,m.fromUserID)),'0000-00-00 00:00:00')
GROUP BY u.id
ORDER BY m.dt
我用了这个,但是我不能按日期排序。另外,如果您在JSON字符串中找到一些“,”,\',\“,则我无法在PHP中读取它
SELECT m.id,
(SELECT CONCAT('{"message":"', m.message, '","myLast":"', IF(m.fromUserID='1',1,0), '", "status":"',m.status,'"}')
FROM messages m
WHERE (m.fromUserID='1' OR m.toUserID='1') AND
(m.fromUserID=u.id OR m.toUserID=u.id)
ORDER BY m.dt DESC
LIMIT 1) AS m,
u.username,
u.id AS usID
FROM messages m
JOIN users u
ON u.id=IF(m.fromUserID='1',m.toUserID,m.fromUserID)
WHERE (m.fromUserID='1' OR m.toUserID='1') AND
m.dt>IFNULL((SELECT d.dt FROM deletechat d WHERE d.userID='1' AND d.withUserID=IF(m.fromUserID='1',m.toUserID,m.fromUserID)),'0000-00-00 00:00:00')
GROUP BY u.id
答案 0 :(得分:1)
问题:我无法按日期排序
除了使用GROUP BY之外,您还可以使用另一个SELECT从当前查询中进行选择:
SELECT r.id, COALESCE(foo.url, bar.url) as url
FROM results r
LEFT JOIN foo USING (url_id)
LEFT JOIN bar USING (url_id)
WHERE foo.url IS NOT NULL OR bar.url IS NOT NULL;
问题:如果您在JSON字符串中找到一些',',\',\“,则无法在PHP中读取
在较新的MYSQL版本中,该功能具有JSON函数,例如JSON_OBJECT() or JSON_QUOTE()。像这样使用:
SELECT * FROM
(SELECT m.id ... /* <-- Your whole query */
...
ORDER BY m.dt DESC /* <-- At the end instead of GROUP BY user ORDER BY */
) as r LIMIT 1 /* <-- Select only the first result, which is the youngest */
对于较早的MySQL版本,您可以使用REPLACE()来转义所有引号等特殊字符。