分组

bkkx9g8r  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(370)

我正在开发定制的电子商务解决方案。我的观点是,我无法获得具有其属性和属性值的产品—按名称分组。例如,用户属于类别\u 01,其中有5种产品。我想向他展示带有可用值的属性过滤器。但只有这5种产品的性能和价值。我可以得到分组属性标题,但我不知道如何也得到分组属性值。

CREATE TABLE `shop_products` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`status` tinyint(1) unsigned NOT NULL DEFAULT '1',
`title` varchar(255) COLLATE utf8_unicode_ci,
`sku` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`price` double(10,4) unsigned NOT NULL,
PRIMARY KEY (`id`)
)

CREATE TABLE `shop_products_properties` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`product_id` int(10) unsigned NOT NULL,
`title` varchar(255) COLLATE utf8_unicode_ci,
`deleted` tinyint(1) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `product_id_foreign` (`product_id`),
CONSTRAINT `product_id_foreign` FOREIGN KEY (`product_id`) 
REFERENCES `shop_products` (`id`) ON DELETE CASCADE
)

CREATE TABLE `shop_products_properties_values` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`property_id` int(10) unsigned NOT NULL,
`value` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`deleted` tinyint(1) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `values_property_id_foreign` (`property_id`),
CONSTRAINT `values_property_id_foreign` FOREIGN KEY (`property_id`) 
REFERENCES `shop_products_properties` (`id`) ON DELETE CASCADE
)

我使用的是laravel,所以我得到的过滤产品有很多属性,有很多值。这很好,但现在我需要按标题对属性进行分组,并按值对它们的值进行分组。
例子:

1.Product
shop_products: T-shirt
shop_products_properties: Color, Size, Material
shop_products_properties_values: Black, Red, White, XS, S, M, Cotton

2.Product
shop_products: Hoodie
shop_products_properties: Color, Size
shop_products_properties_values: Red, Green, White, M, L, XL

我需要得到这样的结果:

Colors: Black, Red, White, Green, White
Sizes: XS, S, M, L, XL
Materials: Cotton

我不知道是否有可能创建mysql查询来得到这个结果,或者我应该过滤和自定义集合。。。如果有任何帮助,我将不胜感激

apeeds0o

apeeds0o1#

假设我正确地解释了您的数据结构,这个查询将执行您想要的操作。

SELECT p.title, GROUP_CONCAT(DISTINCT v.value ORDER BY v.value) AS `values`
FROM shop_products_properties p
LEFT JOIN shop_products_properties_values v
ON v.property_id=p.id
GROUP BY p.title

输出:

title       values
Color       Black,Green,Red,White
Material    Cotton
Size        L,M,S,XL,XS

rextester上的演示

相关问题