I don't know how to order by greater SUM(amount)
IDs from table webhooks
, to fetch messages.
Webhooks Table
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 DATA:
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');
Messages table:
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;
Messages DATA:
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);
Here is my messages query, but i have to order by greatest webhooks amount to_id
SUM(amount)
.
SELECT DISTINCT
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
ORDER BY
time DESC LIMIT $ offset, $ limit
The desired results should be the same as the query, but not to ORDER BY time DESC
but to ORDER BY SUM(amount) DESC
from webhooks
table.
JOIN with the webhooks
table and use GROUP BY from_id, to_id
, then you can order by SUM(amount) DESC
.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.