首页 > 解决方案 > 如何在mysql中搜索多少重复并进行比较

问题描述

所以我想根据它们在 mysql 中有多少重复来比较变量a和变量。b这是我的代码:

query = """ SELECT `do` FROM `foo` """
cursor.execute(query)
result=cursor.fetchall()

a = '0001'
b = '1100'
y = collections.Counter(result)
print(y)

这是我的输出:

Counter({('0001',): 2, ('1100',): 1}, ('0000',): 4})

输出正在计算整行的重复项。我希望它只计算mysql的数量a和数量。b

而且我实际上不知道在此之后该怎么办。
如果a > bprint ,我希望代码运行a
如果a < b打印b

我想要的输出:

a = 2 # number of duplicates
b = 1
a # print a because a > b

任何答案将不胜感激。

标签: pythonpython-3.xmysql-python

解决方案


a = ("0001",)  # Set to tuples so you can directly use them as keys
b = ("1100",)

y = Counter({('0001',): 2, ('1100',): 1, ('0000',): 4})

a_count = y.get(a)  # The number of times `("0001",)` occurs
b_count = y.get(b)  # The number of times `("1100",)` occurs

if a_count > b_count:
    print(a)
elif a_count < b_count:
    print(b)

推荐阅读