check_buyer_nature_field.py 4.47 KB
#!/usr/bin/env python3
"""检查 buy_buyer 表是否有 buyer_nature 字段"""

import os
import pymysql
import sys
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
from config.offline_config import DB_CONFIG

def check_buyer_nature():
    """检查 buyer_nature 字段"""
    try:
        connection = pymysql.connect(
            host=DB_CONFIG['host'],
            port=int(DB_CONFIG['port']),
            user=DB_CONFIG['username'],
            password=DB_CONFIG['password'],
            database=DB_CONFIG['database'],
            charset='utf8mb4'
        )

        with connection.cursor() as cursor:
            # 1. 检查表结构中是否有 buyer_nature 字段
            print("=" * 100)
            print("【检查 buy_buyer 表是否有 buyer_nature 相关字段】")
            print("=" * 100)
            
            sql = "DESCRIBE buy_buyer"
            cursor.execute(sql)
            result = cursor.fetchall()

            print("\n包含 'nature' 或 'type' 的字段:")
            for row in result:
                field_name = row[0]
                if 'nature' in field_name.lower() or 'type' in field_name.lower():
                    print(f"  - {field_name}")

            # 2. 查询是否有以 nature_ 开头的字段
            sql = """
            SELECT id, name, buyer_nature, nature_of_company, customer_type
            FROM buy_buyer
            WHERE is_delete = 0
            LIMIT 10
            """
            
            print("\n" + "=" * 100)
            print("【尝试查询 buyer_nature 字段】")
            print("=" * 100)
            
            try:
                cursor.execute(sql)
                result = cursor.fetchall()
                
                print(f"{'ID':<10} {'name':<30} {'buyer_nature':<15} {'nature_of_company':<20} {'customer_type':<15}")
                print("-" * 100)
                
                for row in result:
                    id_val = str(row[0])
                    name = row[1][:27] if row[1] else 'NULL'
                    buyer_nature = str(row[2]) if row[2] is not None else 'NULL'
                    nature_of_company = str(row[3]) if row[3] is not None else 'NULL'
                    customer_type = str(row[4]) if row[4] is not None else 'NULL'
                    
                    print(f"{id_val:<10} {name:<30} {buyer_nature:<15} {nature_of_company:<20} {customer_type:<15}")
                    
            except Exception as e:
                print(f"查询失败: {e}")

            # 3. 如果有 buyer_nature 字段,查询其分布
            print("\n" + "=" * 100)
            print("【buyer_nature 字段值分布(如果存在)】")
            print("=" * 100)
            
            sql_distinct = """
            SELECT buyer_nature, COUNT(*) as count
            FROM buy_buyer
            WHERE is_delete = 0 AND buyer_nature IS NOT NULL
            GROUP BY buyer_nature
            ORDER BY count DESC
            """
            
            try:
                cursor.execute(sql_distinct)
                result = cursor.fetchall()
                
                if result:
                    print(f"{'buyer_nature':<15} {'数量':>10}")
                    print("-" * 30)
                    
                    for row in result:
                        val = str(row[0])
                        count = row[1]
                        print(f"{val:<15} {count:>10,}")
                        
                        # 查询示例
                        sql_sample = """
                        SELECT id, name, countries
                        FROM buy_buyer
                        WHERE buyer_nature = %s AND is_delete = 0
                        LIMIT 3
                        """
                        cursor.execute(sql_sample, (row[0],))
                        samples = cursor.fetchall()
                        
                        if samples:
                            print(f"  示例:")
                            for s in samples:
                                print(f"    - [{s[0]}] {s[1][:30]} (国家:{s[2]})")
                else:
                    print("  buyer_nature 字段不存在或全部为NULL")
                    
            except Exception as e:
                print(f"查询失败: {e}")

    except Exception as e:
        print(f"查询失败: {e}")
        import traceback
        traceback.print_exc()
    finally:
        if 'connection' in locals():
            connection.close()

if __name__ == "__main__":
    check_buyer_nature()