我需要帮助来了解如何仅显示每个分支最常见的产品。
这适用于数据库中的每个分支。
PS:这是在一张表中完成的(本次表演不需要其他表),只需要提到的两个属性。
根据 Sean 的 DB 示例,我创建了查询,它可以完成这项工作,但是请注意,您在应用程序中的运行方式看起来很耗费资源。尝试考虑另一种方法来发现最常见的产品,而不是数据库查询。
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
将计数放在子查询中,按计数 DESC 排序,然后在该子查询之外按分支 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');