您好大家今天我得到了一个问题..mysql命令通过分组
第一件事,我有两个表中的每个表,我有“product_seq_id”一栏,我加入了表使用相同的“product_seq_id” 第二个表有用于“product_seq_id”我想只有一个低于条件
- table2.date_start不为空的多个行
- table2.date_start等于“0000-00-00”或table2.date_start < = CURDATE()
- table2.date_end等于 '0000-00-00' 或table2.date_start> = CURDATE()
- 获得最高table2.priority如果2个或更多的行当天
我已经匹配做了一些工作..但问题是,它不是以最高优先级的数量,同时与排序列分组
//我的查询
SELECT
psp . *, pcp . *
FROM
sk_product_category_path pcp
left join
sk_product_special_price psp ON (psp.product_seq_id = pcp.product_seq_id)
where
pcp.category_seq_id = 146
AND psp.product_seq_id IS NOT NULL
AND CASE
WHEN
psp.date_start IS NOT NULL
THEN
(psp.date_start = '0000-00-00'
OR psp.date_start <= CURDATE())
AND (psp.date_end = '0000-00-00'
OR psp.date_end >= CURDATE())
ELSE 1 = 1
END
group by psp.product_seq_id
order by psp.priority desc
Result Came for above code:
# product_special_price_seq_id, product_special_price, date_start, date_end, priority, product_seq_id, product_category_path_seq_id, product_seq_id, category_seq_id
2309 123123 0000-00-00 0000-00-00 0 3196 1 3196 146
2307 12313 0000-00-00 0000-00-00 0 3197 3 3197 146
Result I wanted:
# product_special_price_seq_id, product_special_price, date_start, date_end, priority, product_seq_id, product_category_path_seq_id, product_seq_id, category_seq_id
2309 12200 0000-00-00 0000-00-00 1 3196 2 3196 146
2307 12313 0000-00-00 0000-00-00 0 3197 3 3197 146
//表数据
CREATE TABLE IF NOT EXISTS `sk_product_category_path` (
`product_category_path_seq_id` int(11) NOT NULL AUTO_INCREMENT,
`product_seq_id` int(11) NOT NULL,
`category_seq_id` int(11) NOT NULL,
PRIMARY KEY (`product_category_path_seq_id`),
UNIQUE KEY `product_seq_id` (`product_seq_id`,`category_seq_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;
INSERT INTO `sk_product_category_path` (`product_category_path_seq_id`, `product_seq_id`, `category_seq_id`) VALUES
(1, 3196, 146),
(2, 3197, 146),
(3, 3198, 146);
CREATE TABLE IF NOT EXISTS `sk_product_special_price` (
`product_special_price_seq_id` int(11) NOT NULL AUTO_INCREMENT,
`product_special_price` bigint(20) DEFAULT NULL,
`date_start` date DEFAULT NULL,
`date_end` date DEFAULT NULL,
`priority` int(11) DEFAULT NULL,
`product_seq_id` int(11) NOT NULL,
PRIMARY KEY (`product_special_price_seq_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;
INSERT INTO `sk_product_special_price` (`product_special_price_seq_id`, `product_special_price`, `date_start`, `date_end`, `priority`, `product_seq_id`) VALUES
(1, 12313, '0000-00-00', '0000-00-00', 0, 3197),
(2, 12200, '2014-02-11', '2014-02-11', 1, 3197),
(3, 123123, '0000-00-00', '0000-00-00', 0, 3196);
您正在使用的是MySQL'组by'扩展,它允许在聚合查询的'select'未聚集列。由于MySQL *在组中的所有行(http://dev.mysql.com/doc/refman/5.7/en/group-by-extensions.html)中的值不同时警告不要这样做,所以I认为你应该修复你的查询以避免这种不受支持的行为。 –
问题在于你的团队......大多数其他SQL语言实际上会抛出一个错误,而不是执行你所拥有的。 group by语句必须包含select语句中不是某种形式的聚合的所有行。选择psp。*,pcp。*,只有psp.product_seq_id才能在这里工作...无论如何,MySQL足够愚蠢地尝试运行它(返回不正确的结果而不是错误)。 – Twelfth