这是我目前正在做的简化版本。
一个)
SELECT id, foreign_key_id, type, quantity, MAX(price) AS price // <--- Max
FROM quotes
WHERE type = 'tier 1' // <--- Equal
AND prod_id_requested = 12345
二)
SELECT id, foreign_key_id, type, quantity, MAX(price) AS price // <--- Max
FROM quotes
WHERE type != 'tier 1' // <--- NOT equal
AND prod_id_requested = 12345
C)
SELECT id, foreign_key_id, type, quantity, MIN(price) AS price // <--- Min
FROM quotes
WHERE type = 'tier 1' // <--- Equal
AND prod_id_requested = 12345
D)
SELECT id, foreign_key_id, type, quantity, MIN(price) AS price // <--- Min
FROM quotes
WHERE type != 'tier 1' // <--- NOT equal
AND prod_id_requested = 12345
有没有一种好方法可以让我节省一些资源并将这些资源组合成更少的查询?
或者这几乎就是这样做的方法?
[更新]
这里有一些示例数据可供使用:
CREATE TABLE IF NOT EXISTS `quote_item` (
`id` int(2) unsigned NOT NULL AUTO_INCREMENT,
`quote_id` int(2) unsigned NOT NULL,
`product_id_quoted` int(3) unsigned NOT NULL,
`product_id_requested` int(3) unsigned NOT NULL,
`type` varchar(52) DEFAULT NULL,
`price` float(10,4) NOT NULL,
`quantity` int(9) unsigned NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
INSERT INTO `quote_item` (`id`, `quote_id`, `product_id_quoted`, `product_id_requested`, `type`, `price`, `quantity`) VALUES
(1, 1, 12, 12, 'tier 1', 0.0100, 100),
(2, 2, 1, 12, 'tier 3', 0.0038, 8200),
(3, 2, 13, 12, 'tier 2', 0.0041, 10000),
(4, 3, 7, 14, 'tier 1', 0.0060, 25000),
(5, 3, 8, 12, NULL, 0.0180, 250),
(6, 3, 9, 15, NULL, 0.0019, 5000),
(7, 4, 12, 12, NULL, 0.0088, 7500),
(8, 4, 16, 12, 'tier 1', 0.0040, 10000),
(9, 5, 12, 9, 'tier 2', 0.0089, 1200),
(10, 5, 12, 12, 'tier 1', 0.0072, 6400);
最终,我们希望将所有数据很好地打包到一个数组中。
目前,我们从每个查询(无分组)中获取一行,其中我们具有实际ID、Qty等...对于具有最小值的单行,以及具有最高价格的单行的相同信息,每个“类型”类别,然后构建数组。
例如:
$flash_report = array(
'tier1' => array(
'qty' => array(
'min' => array(
'id' => 1
,'quote_id' => 1
,'price' => 0.01
,'quantity' => 100
)
,'max' => array(
'id' => 8
,'quote_id' => 4
,'price' => 0.004
,'quantity' => 10000
)
,'sum' => array(
'value' => 16500
,'count' => 3
)
)
,'price' => array(
'min' => array(
'id' => 8
,'quote_id' => 4
,'price' => 0.004
,'quantity' => 10000
)
,'max' => array(
'id' => 1
,'quote_id' => 1
,'price' => 0.01
,'quantity' => 100
)
)
)
,'other' => array(
'qty' => array(
'min' => array(
'id' => 5
,'quote_id' => 3
,'price' => 0.018
,'quantity' => 250
)
,'max' => array(
'id' => 3
,'quote_id' => 2
,'price' => 0.0041
,'quantity' => 10000
)
,'sum' => array(
'value' => 25950
,'count' => 4
)
)
,'price' => array(
'min' => array(
'id' => 2
,'quote_id' => 2
,'price' => 0.0038
,'quantity' => 8200
)
,'max' => array(
'id' => 5
,'quote_id' => 3
,'price' => 0.018
,'quantity' => 250
)
)
)
)
[ /更新]
现在,我正在从我们各自的查询中获取所有数据,然后将它们全部组装成一个大数组。
我认为必须有更好的方法来做到这一点:)