我在MySQL 8中有3个相关表:
CREATE TABLE `products` (
`id` bigint unsigned NOT NULL AUTO_INCREMENT,
`title` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`status` enum('D','P','A','I') COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'D' COMMENT ' D => Draft, P=>Pending Review, A=>Active, I=>Inactive',
`sale_price` int unsigned DEFAULT NULL,
...
CREATE TABLE `discount_product` (
`id` bigint unsigned NOT NULL AUTO_INCREMENT,
`product_id` bigint unsigned NOT NULL,
`discount_id` tinyint unsigned NOT NULL,
...
CREATE TABLE `discounts` (
`id` tinyint unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL,
`active` tinyint(1) NOT NULL DEFAULT '0',
`min_qty` int unsigned DEFAULT NULL,
`max_qty` int unsigned DEFAULT NULL,
`percent` decimal(7,2) unsigned NOT NULL,
`description` mediumtext COLLATE utf8mb4_unicode_ci NOT NULL,
...
我需要在第2栏中显示相关折扣的产品;
我有两个工作要求.占位符为‘Discount_Info Content’的第一名:
SELECT products.id, products.title, products.sale_price,
GROUP_CONCAT('discount_info content') AS discount_info
FROM products WHERE has_discount_price = 1 AND id = 13
GROUP BY products.id, products.title, products.sale_price
和按产品ID提供的第二次折扣:
SELECT CONCAT(discounts.name, ': ', discounts.min_qty, ': ', discounts.max_qty, ': ', discounts.percent)
FROM discounts, discount_product WHERE discount_product.discount_id = discounts.id AND discount_product.product_id = 13
两个请求都可以.
但是,当我使用GROUP_CONCAT将第二个请求插入到第一个请求的‘discount_info content’占位符中时:
SELECT products.id, products.title, products.sale_price,
GROUP_CONCAT(SELECT CONCAT(discounts.name, ': ', discounts.min_qty, ': ', discounts.max_qty, ': ', discounts.percent)
FROM discounts, discount_product WHERE discount_product.discount_id = discounts.id AND discount_product.product_id = 13) AS discount_info
FROM products WHERE has_discount_price = 1 AND id = 13
GROUP BY products.id, products.title, products.sale_price
我收到错误:
SQL Error [1064] [42000]: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FROM discounts, discount_product WHERE discount_product.discount_id = discounts.' at line 3
如果我从GROUP_CONCAT内部删除了SELECT,但得到了相同的错误.
我为什么会出现这个错误,以及如何修复它? 看起来我误解了GROUP_CONCAT的工作原理.