gpt4 book ai didi

mysql - 查询优化 - 在 SQL 中高效地整理一对多关系表的结果

转载 作者:行者123 更新时间:2023-11-29 02:21:13 27 4
gpt4 key购买 nike

我正在尝试组合一对多表。我想一起显示一个项目的变体。这必须完全在 SQL 中完成。

这是示例架构

CREATE TABLE ItemVariant (`item_id` int, `variant_id` int, `variant` varchar(55), `variant_order` int);
INSERT INTO ItemVariant (`variant_id`, `item_id`, `variant`, `variant_order`)
VALUES
(1, 1, 'I1V1', 1),
(2, 1, 'I1V2', 2),
(3, 1, 'I1V3', 3),
(4, 2, 'I2V1', 1)
;

CREATE TABLE Item (`item_id` int, `item` varchar(55));
INSERT INTO Item (`item_id`, `item`)
VALUES (1,'I1'), (2,'I2');

这是一个有效的查询,它为我提供了所需的信息。 SQLFiddle

SELECT Item.item, iv1.variant, iv2.variant, iv3.variant from Item
LEFT JOIN ItemVariant iv1 ON (Item.item_id = iv1.item_id and iv1.variant_order=1)
LEFT JOIN ItemVariant iv2 ON (Item.item_id = iv2.item_id and iv2.variant_order=2)
LEFT JOIN ItemVariant iv3 ON (Item.item_id = iv3.item_id and iv3.variant_order=3)

但是,如您所见,我必须访问 ItemVariant 表 3 次,因此效率不高。我想过使用 group by 但我无法在 group by 形成的组内查询。

这是我为分组依据所尝试的。 SQLFiddle

SELECT 
*,
case when variant_order=1 then variant end as variant1,
case when variant_order=2 then variant end as variant2,
case when variant_order=3 then variant end as variant3
from ItemVariant
GROUP BY item_id

最佳答案

试试这个:

SELECT Item.item, 
MAX(case when variant_order=1 then variant end) as variant1,
MAX(case when variant_order=2 then variant end) as variant2,
MAX(case when variant_order=3 then variant end) as variant3
from ItemVariant
LEFT JOIN Item ON Item.item_id = ItemVariant.item_id
GROUP BY Item.item;

关于mysql - 查询优化 - 在 SQL 中高效地整理一对多关系表的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31603290/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com