MYSQL选择查询最常见的产品?

Mar*_*gea 5 mysql count max

我需要帮助找出如何只为每个分支显示最常用的产品.

这适用于DB中的每个分支.

PS:这是在一个表中完成的(此性能不需要其他表),并且只需要提到的两个属性.

Sea*_*ean 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
Run Code Online (Sandbox Code Playgroud)

产量:

+-----------+----------------+-----+
| branch_id | branch_product | cou |
+-----------+----------------+-----+
|         1 | trainers       |   3 |
|         2 | suit           |   2 |
|         3 | suit           |   1 |
+-----------+----------------+-----+
3 rows in set (0.00 sec)
Run Code Online (Sandbox Code Playgroud)

这是一个用于尝试上述查询的示例表:

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');
Run Code Online (Sandbox Code Playgroud)