K
K
Kirill Petrov2019-11-07 14:55:47
MySQL
Kirill Petrov, 2019-11-07 14:55:47

How to correctly compose a query in MySQL, presenting a table with parameters as a value column?

Greetings. There is a sign:

CREATE TABLE `applications_custom_var` (
  `applications_custom_var_id` int(11) NOT NULL,
  `id` int(11) NOT NULL,
  `param` varchar(244) NOT NULL,
  `value` varchar(244) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO `applications_custom_var` (`applications_custom_var_id`, `id`, `param`, `value`) VALUES
(1, 300000, 'z1', '1'),
(2, 300000, 'z2', '2'),
(3, 300001, 'z1', '3'),
(4, 300001, 'z4', '22'),
(5, 300000, 'z4', 'vasya');

ALTER TABLE `applications_custom_var`
  ADD PRIMARY KEY (`applications_custom_var_id`),
  ADD KEY `id` (`id`),
  ADD KEY `id_param` (`id`,`param`);

ALTER TABLE `applications_custom_var`
  MODIFY `applications_custom_var_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6;

5dc404ff06d0f866125711.png
And I want to get the names of the parameters in the columns. Like this:
5dc4056e0aae8091932040.png
And I came up with a SQL query that does this:
SELECT 
`id`, 
GROUP_CONCAT(IF(param = 'z1', `value`, null)) AS `z1`, 
GROUP_CONCAT(IF(param = 'z2', `value`, null)) AS `z2`, 
GROUP_CONCAT(IF(param = 'z3', `value`, null)) AS `z3`, 
GROUP_CONCAT(IF(param = 'z4', `value`, null)) AS `z4`
FROM `applications_custom_var`
WHERE `id` IN(300000, 300001)
GROUP BY `id`

But it seems to me that GROUP_CONCAT is used only for debugging and can cause brakes with large data, since I want to join the results in the future. In general, did I correctly compose the request or is it necessary / possible somehow differently?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
Lazy @BojackHorseman MySQL, 2019-11-07
@Recosh

you can use MIN instead of GROUP_CONCAT)
that's just the trouble. with such a scheme, it will be necessary to rewrite the query for each new parameter)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question