CREATE TABLE IF NOT EXISTS `live_product` (
`id` int(11) unsigned NOT NULL,
`product_details` text NOT NULL,
`price` decimal(10,2) NOT NULL,
`tag1` varchar(255) NOT NULL,
`tag2` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=8 ;
INSERT INTO `live_product` (`id`, `product_details`, `price`, `tag1`, `tag2`) VALUES
(1, 'Product 1', '302.54', 'man,boy,girl', '22'),
(2, 'Product 2', '457.00', 'man,girl', '22'),
(3, 'Product 3', '157.00', 'girl', '24'),
(4, 'Product 4', '1157.00','man,boy,girl', '22'),
(5, 'Product 5', '957.00', 'man,boy,girl', '22'),
(6, 'Product 6', '757.00', 'boy,girl', '22'),
(7, 'Product 7', '157.00', 'boy', '24');
高级搜索的2个mysql查询需要2个结果
+------+-------------+ | Tag1 | Total_Count | +------+-------------+ | girl | 6 | | man | 4 | +------+-------------+
+----+-----------------+---------+--------------+------+ | id | product_details | price | tag1 | tag2 | +----+-----------------+---------+--------------+------+ | 1 | Product 1 | 302.54 | man,boy,girl | 22 | | 2 | Product 2 | 457.00 | man,girl | 22 | | 3 | Product 3 | 157.00 | girl | 24 | | 4 | Product 4 | 1157.00 | man,boy,girl | 22 | | 5 | Product 5 | 957.00 | man,boy,girl | 22 | | 6 | Product 6 | 757.00 | boy, girl | 22 | +----+-----------------+---------+--------------+------+
SELECT t.tag1 as Tag1, count(*) AS Total_Count FROM
(SELECT
live_product.id,
SUBSTRING_INDEX(SUBSTRING_INDEX(live_product.tag1, ',', numbers.n), ',', -1) tag1
FROM
(SELECT 1 n UNION ALL SELECT 2
UNION ALL SELECT 3 UNION ALL SELECT 4) numbers INNER JOIN live_product
ON CHAR_LENGTH(live_product.tag1)
-CHAR_LENGTH(REPLACE(live_product.tag1, ',', ''))>=numbers.n-1
ORDER BY
id, n) t
GROUP BY t.tag1
ORDER BY Total_Count DESC, t.tag1 ASC;
以上查询仅提供逗号分隔计数,但当我在价格之间添加更多条件时,它会给出错误的结果。
答案 0 :(得分:0)
尝试一下,如果它适合你 -
SELECT b.sub AS Tag1, COUNT(a.id) AS Total_Count FROM
live_product a
JOIN
(
SELECT SUBSTRING_INDEX(tag1,',',1) sub FROM live_product UNION
SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(tag1,',',2),',',-1) sub FROM live_product UNION
SELECT SUBSTRING_INDEX(tag1,',',-1) FROM live_product sub
) b ON FIND_IN_SET(b.sub,a.tag1)
GROUP BY b.sub;