我有三个产品表,产品配置(如iPhone x 64黑色、iPhone x 64红色)和产品库存;我想选择所有产品并按价格(在配置表中)和可用性(在库存表中)排序,但每个产品只能得到一行;我该怎么做?
CREATE TABLE `product_inventories` (
`inventory_id` bigint(20) NOT NULL,
`quantity` int(11) NOT NULL,
`warehouse_id` bigint(20) DEFAULT NULL,
`config_id` bigint(20) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
CREATE TABLE `product_configs` (
`config_id` bigint(20) NOT NULL,
`product_id` bigint(20) DEFAULT NULL,
`price` decimal(12,3) DEFAULT NULL,
`discount_percent` int(11) DEFAULT NULL,
`sku` varchar(30) DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8 ROW_FORMAT=FIXED;
CREATE TABLE `products` (
`id` bigint(20) NOT NULL,
`title` varchar(255) DEFAULT NULL,
`category_id` bigint(20) NOT NULL,
) ENGINE=MyISAM DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC;
SELECT *
FROM products
LEFT JOIN product_configs ON products.id = product_configs.product_id
LEFT JOIN product_inventories inventories ON inventories.inventory_id =
(SELECT product_inventories.inventory_id from product_inventories
WHERE product_inventories.config_id = product_configs.config_id
ORDER by product_inventories.quantity DESC LIMIT 1 )
ORDER BY product_configs.price ASC, inventories.quantity DESC
编辑:
SELECT *
FROM products
LEFT JOIN product_configs ON products.id = product_configs.product_id
LEFT JOIN product_inventories inventories ON inventories.inventory_id =
(SELECT product_inventories.inventory_id from product_inventories
WHERE product_inventories.config_idd = product_configs.config_id
ORDER by product_inventories.quantity DESC LIMIT 1 )
ORDER BY product_configs.price is null, product_configs.price ASC, inventories.quantity DESC
我有以下结果;但我希望每个配置有一个最低价格和最高数量的产品