我需要帮助找出如何只为每个分支显示最常用的产品。
这适用于DB中的每个分支。
PS:这是在一个表中完成的(此性能不需要其他表),只需要提到的两个属性。
答案 0 :(得分:1)
根据Sean的数据库样本,我已经创建了查询,它可以完成这项工作,但请注意,您在应用程序中使用的方式看起来很昂贵。尝试考虑另一种方法来发现最常见的产品,而不是数据库查询。
SELECT
a.branch_id, `branch_product` , COUNT(branch_product) AS cnt , b.mx
FROM
branch_products a
LEFT JOIN
(SELECT
branch_id, MAX(cnt) AS mx
FROM
(SELECT branch_id, COUNT(branch_product) AS cnt FROM branch_products GROUP BY branch_id, branch_product ) AS maxes
GROUP BY branch_id) b
ON a.branch_id = b.branch_id
GROUP BY branch_id, branch_product
HAVING cnt=mx
答案 1 :(得分:0)
将计数放在子查询中,ORDER BY计数DESC,然后在子查询GROUP BY之外的分支ID:
SELECT * FROM (
SELECT *, count(branch_product) AS cou FROM branch_products
GROUP BY branch_id, branch_product
ORDER BY cou DESC
) AS ordbycou
GROUP BY branch_id
收率:
+-----------+----------------+-----+
| branch_id | branch_product | cou |
+-----------+----------------+-----+
| 1 | trainers | 3 |
| 2 | suit | 2 |
| 3 | suit | 1 |
+-----------+----------------+-----+
3 rows in set (0.00 sec)
以下是使用以下内容尝试上述查询的示例表:
SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
CREATE TABLE IF NOT EXISTS `branch_products` (
`branch_id` mediumint(8) unsigned NOT NULL,
`branch_product` varchar(128) NOT NULL,
KEY `branch_id` (`branch_id`),
KEY `branch_product` (`branch_product`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
INSERT INTO `branch_products` (`branch_id`, `branch_product`) VALUES
(1, 'trainers'),
(1, 'trainers'),
(1, 'trainers'),
(1, 'tie'),
(1, 'tie'),
(1, 'suit'),
(2, 'suit'),
(2, 'suit'),
(2, 'tie'),
(3, 'suit');