避免具有多个JSON聚合功能的子查询

时间:2018-08-06 08:15:58

标签: mysql yii2

我正在使用yii2框架并尝试建立关系,但是如果可能的话,需要简化查询,以便可以在内部使用。

SQL Fiddle here

我的桌子

CREATE TABLE image (
  id int(11) UNSIGNED NOT NULL,
  type varchar(32) NOT NULL,
  file_id int(11) UNSIGNED NOT NULL,
  device tinyint(4) UNSIGNED NOT NULL,
  PRIMARY KEY (file_id, device, id, type)
)
ENGINE = INNODB,
AVG_ROW_LENGTH = 93,
CHARACTER SET utf8mb4,
COLLATE utf8mb4_unicode_ci;

ALTER TABLE image
ADD UNIQUE INDEX UK_image (id, type, file_id, device);

/* `id` is the PK of related content data */
/* `type` is a string identifier of the image */
/* `file_id` is the PK of the file data */
/* `device` is an identifiery of the device the image is for */
INSERT INTO image (id, type, file_id, device)
    VALUES
    (1, 'item:thumb', 1, 1),
    (1, 'item:thumb', 3, 2),
    (1, 'item:thumb', 2, 3),
    (1, 'item:thumb', 4, 1),
    (2, 'item:thumb', 1, 1);

有效的查询

SELECT id, JSON_OBJECTAGG(b.type, b.o) AS images
  FROM (
      SELECT id, type, JSON_OBJECTAGG(a.device, a.f) AS o
    FROM (
      SELECT id, type, device, JSON_ARRAYAGG(i.file_id) AS f
        FROM image i
        WHERE i.id IN (1, 2) AND i.type IN ('item:thumb')
        GROUP BY i.id, i.type , i.device
    ) a
    GROUP BY id, a.type
  ) b
  GROUP BY b.id;

我希望能奏效,但会出现有关组功能的错误。

SELECT id, JSON_OBJECTAGG(i.type, JSON_OBJECTAGG(i.device, JSON_ARRAYAGG(i.file_id))) AS f
    FROM image i
    WHERE i.id IN (1, 2) AND i.type IN ('item:thumb')
    GROUP BY i.id, i.type , i.device;

获得结果

  • {“ item:thumb”,{“ 1”:[1,4],“ 2”:[3],“ 3”:[2]}}
  • {“ item:thumb”,{“ 1”:[1]}}

0 个答案:

没有答案
相关问题