N
N
NetyNicka2015-08-20 14:22:42
MySQL
NetyNicka, 2015-08-20 14:22:42

How to parse json string in SQL query and use it for sorting?

Good day comrades! Once again, your ambulance is needed 8)
There is a sql query:

SELECT
  `resources`,
  `command`,
  `timestamp`
FROM
  `command`
WHERE
  (
    (
      (`user_id` = 1000196805)
      AND (
        `command`.`resources` LIKE '%\"14\":%'
      )
    )
    AND (`timestamp` >= 1439856000)
  )
AND (`timestamp` <= 1439942400)
ORDER BY
  `timestamp` DESC

Which outputs this result:
{"2":61,"14":"24"},	energize,	1439856776.5546
{"2":61,"14":24},	buy,	1439856776.0372
{"2":61,"14":25},	energize,	1439856775.2379

The question is how to make it so that the result would be like this:
{"2":61,"14":24},	energize,	1439856776.5546
{"2":61,"14":25},	energize,	1439856775.2379

(Line {"2":61,"14":24}, buy, 1439856776.0372 deleted because "14":24 occurred 2 times) Workaround
:
SELECT
DISTINCT
  `resources`,
  `command`,
  `timestamp`,
REPLACE(SUBSTRING_INDEX(SUBSTRING_INDEX(SUBSTRING_INDEX(resources, ',', 2), ',' , -1 ), ':', -1), '"','') as dist
FROM
  `command`
WHERE
  (
    (
      (`user_id` = 1000196805)
      AND (
        `command`.`resources` LIKE '%\"14\":%'
      )
    )
    AND (`timestamp` >= 1439856000)
  )
AND (`timestamp` <= 1439942400)
GROUP BY dist
ORDER BY
  `timestamp` DESC

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexey Ukolov, 2015-08-20
@NetyNicka

DISTINCT won't help here, GROUP BY must be used.

SELECT
  `resources`,
  `command`,
  MAX(`timestamp`)
FROM
  `command`
WHERE
  (
    (
      (`user_id` = 1000196805)
      AND (
        `command`.`resources` LIKE '%\"14\":%'
      )
    )
    AND (`timestamp` >= 1439856000)
  )
AND (`timestamp` <= 1439942400)
ORDER BY
  `timestamp` DESC
GROUP BY
  `resources`

But mysql does not guarantee what will be returned in command in this query - when grouping, you need to use in SELECT only those fields by which grouping or aggregate functions are performed (MAX, for example, as in this query).

E
Evgeniy Zavyalov, 2015-08-20
@profit

first, explain why you need to remove
{"2":61,"14":24}, buy, 1439856776.0372
and not
{"2":61,"14":24}, energize, 1439856776.5546
because the request can return in other sequence!?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question