从另一个表ID中排序mysql数据
我不知道如何从表从另一个表ID中排序mysql数据,mysql,Mysql,我不知道如何从表webhooks中按更大的SUM(amount)id排序以获取消息 网钩表 CREATE TABLE `webhooks` ( `id` int(200) NOT NULL, `created_at` varchar(40) NOT NULL, `amount` double NOT NULL, `from_id` varchar(20) NOT NULL, `to_id` varchar(20) NOT NULL, ) ENGINE=InnoDB DEFAU
webhooks
中按更大的SUM(amount)
id排序以获取消息
网钩表
CREATE TABLE `webhooks` (
`id` int(200) NOT NULL,
`created_at` varchar(40) NOT NULL,
`amount` double NOT NULL,
`from_id` varchar(20) NOT NULL,
`to_id` varchar(20) NOT NULL,
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
webhooks数据:
INSERT INTO `webhooks` (`to_id`, `from_id`, `amount`, `created_at`) VALUES
('1273817', '15992', 9.99, '1605642691'),
('1273817', '11813', 8, '1605642189'),
('38218', '47348', 5.99, '1605642142'),
('188277', '39123', 8, '1605641928'),
('188277', '47348', 10, '1605639932');
消息表:
CREATE TABLE `messages` (
`id` int(255) NOT NULL,
`to_id` int(20) NOT NULL,
`from_id` int(20) NOT NULL,
`message` longtext NOT NULL,
`time` double NOT NULL,
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
信息数据:
INSERT INTO `messages` (`from_id`, `to_id`, `message`, `time`) VALUES
(1273817, 43802, 'Hey there how are you', 1605643518.3869),
(46804, 1273817, 'Hello there!!', 1605643487.5376),
(45937, 1273817, 'Wowww', 1605642552.2655),
(47348, 38218, 'yayyy!!!', 1605642523.0497),
(47348, 43802, 'Are you there?', 1605640241.813);
这是我的邮件查询,但我必须按最大webhooks金额到\u id
总和(金额)
排序
所需的结果应与查询相同,但不是按时间顺序描述,而是从
webhooks
表中按总和(金额)描述进行排序。与webhooks
表连接并使用分组方式from\u id,to\u id
,然后可以按总和(金额)描述进行排序
SELECT
c.from_id,
c.to_id
FROM
messages c
JOIN
(
SELECT
CASE
WHEN
`from_id` = '$uid'
THEN
`to_id`
ELSE
`from_id`
END
AS other, MAX(time) AS latest
FROM
messages
WHERE
(
`from_id` = '$uid'
OR `to_id` = '$uid'
)
AND to_id != '0'
GROUP BY
other
)
m
ON (c.from_id = '$uid'
AND c.to_id = m.other
OR c.to_id = '$uid'
AND c.from_id = m.other)
AND c.time = m.latest
LEFT JOIN (
SELECT 0 + from_id AS from_id_int, 0 + to_id AS to_id_int, SUM(amount) AS amount
FROM webhooks
GROUP BY from_id, to_id
) AS w ON w.from_id_int = c.from_id AND w.to_id_int = c.to_id
ORDER BY w.amount DESC
LIMIT $offset, $limit
提示:不要执行literal
“$uid”
,而是执行?
,然后将值绑定到这些值。@tadman感谢您的提示。请参阅与webhooks
表连接,然后按顺序使用所需的列。请显示此示例数据的结果。注释不用于扩展讨论;这段对话已经结束。
SELECT
c.from_id,
c.to_id
FROM
messages c
JOIN
(
SELECT
CASE
WHEN
`from_id` = '$uid'
THEN
`to_id`
ELSE
`from_id`
END
AS other, MAX(time) AS latest
FROM
messages
WHERE
(
`from_id` = '$uid'
OR `to_id` = '$uid'
)
AND to_id != '0'
GROUP BY
other
)
m
ON (c.from_id = '$uid'
AND c.to_id = m.other
OR c.to_id = '$uid'
AND c.from_id = m.other)
AND c.time = m.latest
LEFT JOIN (
SELECT 0 + from_id AS from_id_int, 0 + to_id AS to_id_int, SUM(amount) AS amount
FROM webhooks
GROUP BY from_id, to_id
) AS w ON w.from_id_int = c.from_id AND w.to_id_int = c.to_id
ORDER BY w.amount DESC
LIMIT $offset, $limit