大家好,今天我遇到了一个问题..
首先我有两个表,每个表都有“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()
- 如果同一天有 2 行或更多行匹配,则获得最高的 table2.priority
我已经做了一些工作..但问题在于,在对分组进行排序时,它没有采用最高优先级编号
//我的查询
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 中的 GROUP BY
期间,除非您使用聚合函数,否则它会为每个组选择第一个匹配的行。第一个匹配不必总是带有 min(id) 的行。
可能的查询应该类似于:
SELECT t.*
from table_name t
inner join (
select min(id) as id
from table_name t
group by col) as s
on s.id = t.id
关于Mysql 排序依据与分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21707706/