表架构
CREATE TABLE `shops` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`user_id` int(11) DEFAULT NULL,
`shop_code` varchar(60) COLLATE utf8mb4_unicode_ci NOT NULL,
`retailer_name` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`shop_closed_temporarily` tinyint(4) NOT NULL DEFAULT '0',
`verification_status` tinyint(4) NOT NULL DEFAULT '0' COMMENT '0=no-action,1=verified,2=rejected,3=pending',
PRIMARY KEY (`id`)
)
表中的数据
id user_id shop_code retailer_name shop_closed_temporarily verification_status
1 3 XYZ0001 abc 0 3
2 3 XYZ0002 abd 0 3
3 3 XYZ0003 abe 1 2
4 3 XYZ0004 abf 0 1
5 3 XYZ0005 abf 0 3
6 3 XYZ0005 abf 0 3
问题:
我想获取所有不同的“ shop_code”记录,其中verification_status = 3,shop_closed_temporarily = 0。 结果应为所有列。
查询
SELECT
*
FROM
shops s
WHERE s.user_id = 3
AND s.shop_closed_temporarily = 0
AND s.verification_status = 3
GROUP BY s.shop_code
想要实现: 1,2,5 要么 1,2,6 因为第5行和第6行具有相似的shop_code。
答案 0 :(得分:1)
您可以使用聚合函数,例如min()
select min(s.id), s.shop_code
FROM shops s
WHERE s.user_id = 3
AND s.shop_closed_temporarily = 0
AND s.verification_status = 3
GROUP BY s.shop_code
或max()
select max(s.id), s.shop_code
FROM
shops s
WHERE s.user_id = 3
AND s.shop_closed_temporarily = 0
AND s.verification_status = 3
GROUP BY s.shop_code
以及所有列
要获取所有列,您可以使用检索到的id(my_id)将合并查询与表本身的结果联接起来,例如:for max(s.id)
select s1.* from shops s1
inner join
(
select max(s.id) my_id, s.shop_code
FROM
shops s
WHERE s.user_id = 3
AND s.shop_closed_temporarily = 0
AND s.verification_status = 3
GROUP BY s.shop_code
) t on t.my_id = s1.id
答案 1 :(得分:0)
尝试使用不同的
SELECT DISTINCT shop_code FROM `shops`;
返回
shop_code
XYZ0001
XYZ0002
XYZ0003
XYZ0004
XYZ0005