I'm trying to make a link between 2 tables on mySQL but, i think it's a little bit harder than i thought.
I have 3 tables * One which registers my rules informations * One which registers my transfers informations * One which make the pivot between the two first.
CREATE TABLE `rules` (
`id` int,
`Name` varchar(10)
);
INSERT INTO `rules` (`id`, `name`) VALUES
(1,'a'),
(2,'b'),
(3,'c'),
(4,'d');
CREATE TABLE `pivot` (
`id_rule` int,
`id_transfert` int
);
INSERT INTO `pivot` (`id_rule`, `id_transfert`) VALUES
(1,1),
(1,2),
(2,1),
(2,2),
(2,3);
CREATE TABLE `transferts` (
`id` int,
`aeroport` varchar(50),
`station` varchar(50)
);
INSERT INTO `transferts` (`id`, `aeroport`,`station`) VALUES
(1,'GVA','Flaine'),
(2,'GNB','La Tania'),
(3,'GNB','Flaine');
What i'm trying to do is to get all my rules with a column which gather all linked transfers as a JSON string. Like below
------------------------------------------------------------------------ | id | name | transferts | ------------------------------------------------------------------------ | 1 | a | {"GVA": "Flaine"} | ------------------------------------------------------------------------ | 2 | b | {"GVA": "Flaine", "GNB": "Flaine", "La Tania"} | ------------------------------------------------------------------------
What i do actually is this :
SELECT rule.id, rule.name,GROUP_CONCAT(stations.transferts SEPARATOR ",") as transferts FROM rules rule LEFT OUTER JOIN pivot pivot on (pivot.id_rule = rule.id) LEFT OUTER JOIN ( SELECT id, CONCAT(aeroport, ":", GROUP_CONCAT(station) ) AS transferts FROM transferts GROUP BY aeroport ) stations on (pivot.id_transfert = stations.id) GROUP BY rule.id
But this is returning me a "null" value. I don't see what i'm doing wrong. Is there someone who can help me please ?
FYI, I was inspired by this link MySQL: GROUP_CONCAT with LEFT JOIN