外键在一个字段中分隔

时间:2018-08-13 13:53:32

标签: mysql sql json

我有两个表:

tbllocations

ID      |      Name      |  Type
1       | Location1      |  {"0":"23","1":"27","2":"24","3":"22"}
2       | Location2      |  {"0":"22","1":"25"}

tbllocationtypes

ID      |      title      
22      |    Wines
23      |    Milk
24      |    Cereals
25      |    Drinks
26      |    Beef
27      |    Chicken

Type字段(具有这种确切格式)中,类型的外键是特殊分隔的

"0":"Default Foreign Key of tbllocationtype", "1","First additional Foreign Key of tbllocationtype", "2","Second Additional Foreign Key of tbllocaitontype"

我需要一个包含所有位置的列表,其中包含一个包含所有类型的字段:

查询结果:

IDLocation     |   Name       |     Types
1                Location1       Milk,Chicken,Cereals,Wine
2                Location2       Wines,Drinks

能帮我吗?我在MySQL中太糟糕了,无法找出答案。

非常感谢

1 个答案:

答案 0 :(得分:0)

在现代版本的MySQL(> = 8.0.4)中,查询相对简单:

SELECT
  `l`.`id` `IDLocation`,
  `l`.`name` `Name`,
  GROUP_CONCAT(`lt`.`title`) `Types`
FROM
  `tbllocations` `l`,
  JSON_TABLE(`l`.`type`,
    '$.*' COLUMNS(
      `id` BIGINT UNSIGNED PATH '$'
    )
  ) `der`
  INNER JOIN `tbllocationtypes` `lt` ON
    `lt`.`id` = `der`.`id`
GROUP BY
  `l`.`id`,
  `l`.`name`;

请参见db-fiddle

但是,在较早的版本中,这不是一个简单的选择:

SELECT
  `l`.`id` `IDLocation`,
  `l`.`name` `Name`,
  GROUP_CONCAT(`lt`.`title`) `Types`
FROM
  `tbllocationtypes` `lt`
  LEFT JOIN
    `tbllocations` `l` ON
      JSON_CONTAINS(
        JSON_EXTRACT(`l`.`type`, '$.*'),
        JSON_QUOTE(CAST(`lt`.`id` AS CHAR))
      )
WHERE
  `l`.`id` IS NOT NULL
GROUP BY
  `l`.`id`,
  `l`.`name`;

请参见db-fiddle

无论如何,请记住5.1.7 Server System Variables::group_concat_max_len