【问题标题】:How to search for how much duplicate in mysql and compare it如何在mysql中搜索多少重复并进行比较
【发布时间】:2020-01-04 23:32:48
【问题描述】:

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

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 中有多少 ab

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

我想要的输出:

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

任何答案将不胜感激。

【问题讨论】:

    标签: python python-3.x mysql-python


    【解决方案1】:
    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)
    

    【讨论】:

      【解决方案2】:

      您可以使用更复杂的查询来提取您需要的数据,并减少您需要在 Python 中完成的工作量。

      对于WHERE 子句中指定的do 值,此查询提取do 的值以及包含do 值的行数。

      stmt = """SELECT do, COUNT(do)
                FROM foo
                WHERE do IN ('0001', '1100')
                GROUP BY do;"""
      cursor.execute(stmt)
      result=cursor.fetchall()   # [('0001', 2), ('1100', 1)]
      
      largest = max(result, key=lambda x: x[1])
      print(largest[0])
      

      或者您可以在数据库中完成所有工作。此查询与上一个查询一样对值及其行数进行分组,但按行数的降序对它们进行排序,并返回第一行。

      stmt = """SELECT do, COUNT(do) AS do_count 
                FROM foo 
                WHERE do IN ('0001', '1100') 
                GROUP BY do 
                ORDER BY do_count DESC 
                LIMIT 1;"""
      cur.execute(stmt)
      result = cursor.fetchone()    # ('0001', 2)
      print(result[0])    
      

      请注意,这两种方法都假定不会有两个具有相同行数的 do 值,问题中的代码也是如此。如果代码要处理这种情况,则必须在第一个示例中的 max 或第二个示例中的 ORDER BY 子句的键函数中指定其他排序条件。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-12-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-12-02
        • 1970-01-01
        相关资源
        最近更新 更多