diff --git a/offline_tasks/test/buyer_type_summary.py b/offline_tasks/test/buyer_type_summary.py new file mode 100644 index 0000000..5830cd0 --- /dev/null +++ b/offline_tasks/test/buyer_type_summary.py @@ -0,0 +1,157 @@ +#!/usr/bin/env python3 +"""总结 buy_buyer 表的客户类型字段情况""" + +import os +import pymysql +import sys +sys.path.append(os.path.dirname(os.path.abspath(__file__))) +from config.offline_config import DB_CONFIG + +def summarize_buyer_type(): + """总结客户类型字段""" + 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: + print("=" * 120) + print(" buy_buyer 表客户类型字段总结") + print("=" * 120) + + print("\n【问题】哪个字段表示客户类型(商超、品牌、批发商等)?") + print("\n【答案】") + + print("\n" + "=" * 120) + print("1. 字典表中定义的客户类型(buyer_nature)") + print("=" * 120) + print("在 pub_dict_item 中有 buyer_nature 字典,包含以下客户类型:") + print(" code | name") + print("-------|----------------------------------") + print(" 1 | 贸易公司") + print(" 2 | 零售商(包含商超)") + print(" 3 | 批发商") + print(" 4 | 分销商") + print(" 5 | 代理商") + print(" 6 | 自有品牌") + print(" 7 | 其他") + + print("\n" + "=" * 120) + print("2. buy_buyer 表实际存在的字段") + print("=" * 120) + print("⚠️ 注意:buy_buyer 表中并没有 buyer_nature 字段!") + print("\n实际存在的相关字段:") + + # customer_type + print("\n 1) customer_type - 客户类型") + sql = """ + SELECT customer_type, COUNT(*) as count + FROM buy_buyer + WHERE is_delete = 0 + GROUP BY customer_type + ORDER BY customer_type + """ + cursor.execute(sql) + result = cursor.fetchall() + + print(" 值分布:") + for row in result: + val = row[0] if row[0] is not None else 'NULL' + count = row[1] + print(f" - {val}: {count:,} 条") + + print(" ⚠️ 数据稀疏,仅5%的买家有值") + + # nature_of_company + print("\n 2) nature_of_company - 公司类型") + sql = """ + SELECT nature_of_company, COUNT(*) as count + FROM buy_buyer + WHERE is_delete = 0 + GROUP BY nature_of_company + ORDER BY nature_of_company + """ + cursor.execute(sql) + result = cursor.fetchall() + + print(" 值分布:") + for row in result: + val = row[0] if row[0] is not None else 'NULL' + count = row[1] + print(f" - {val}: {count:,} 条") + + print(" ⚠️ 仅有51, 52两个值,字典中无对应定义") + + # buyer_from + print("\n 3) buyer_from - 采购商来源(不是客户类型)") + sql = """ + SELECT buyer_from, COUNT(*) as count + FROM buy_buyer + WHERE is_delete = 0 + GROUP BY buyer_from + ORDER BY buyer_from + """ + cursor.execute(sql) + result = cursor.fetchall() + + print(" 值分布:") + for row in result: + val = row[0] if row[0] is not None else 'NULL' + count = row[1] + print(f" - {val}: {count:,} 条") + + print("\n 字典含义:") + print(" - 1: 展会收集") + print(" - 2: 网络收集") + print(" - 3: 渠道搜集") + print(" - 4: 客户介绍") + print(" - 5: 其他/导入") + print(" - 6: 自行注册") + + # cooperate_type + print("\n 4) cooperate_type - 合作模式") + sql = """ + SELECT cooperate_type, COUNT(*) as count + FROM buy_buyer + WHERE is_delete = 0 + GROUP BY cooperate_type + ORDER BY cooperate_type + """ + cursor.execute(sql) + result = cursor.fetchall() + + print(" 值分布:") + for row in result: + val = row[0] if row[0] is not None else 'NULL' + count = row[1] + print(f" - {val}: {count:,} 条") + + print("\n" + "=" * 120) + print("3. 结论与建议") + print("=" * 120) + print("❌ buy_buyer 表目前没有直接存储「商超、品牌、批发商」这类客户类型") + print("\n✅ 可用的替代方案:") + print(" 1. customer_type - 但数据稀疏,仅5%有值") + print(" 2. nature_of_company - 数据较完整(57%),但只有51/52两个值,含义不明") + print(" 3. buyer_from - 采购商来源,不是客户类型") + print(" 4. cooperate_type - 合作模式,不是客户类型") + print("\n💡 建议:") + print(" 1. 如果需要客户类型分类,可能需要基于其他字段(如采购量、采购频率等)推算") + print(" 2. 或者联系业务方确认 customer_type 和 nature_of_company 的真实含义") + print(" 3. 考虑引入 buyer_nature 字段(字典已定义,表中未使用)") + + except Exception as e: + print(f"查询失败: {e}") + import traceback + traceback.print_exc() + finally: + if 'connection' in locals(): + connection.close() + +if __name__ == "__main__": + summarize_buyer_type() diff --git a/offline_tasks/test/check_buyer_nature_field.py b/offline_tasks/test/check_buyer_nature_field.py new file mode 100644 index 0000000..6120b60 --- /dev/null +++ b/offline_tasks/test/check_buyer_nature_field.py @@ -0,0 +1,124 @@ +#!/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() diff --git a/offline_tasks/test/check_country_fields.py b/offline_tasks/test/check_country_fields.py new file mode 100644 index 0000000..38afdda --- /dev/null +++ b/offline_tasks/test/check_country_fields.py @@ -0,0 +1,77 @@ +""" +检查 sensors_events 表是否有国家相关字段 +""" +import sys +import os +sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +from db_service import create_db_connection +from offline_tasks.config.offline_config import DB_CONFIG +import pandas as pd + +# 创建数据库连接 +print("连接数据库...") +engine = create_db_connection( + DB_CONFIG['host'], + DB_CONFIG['port'], + DB_CONFIG['database'], + DB_CONFIG['username'], + DB_CONFIG['password'] +) + +print("\n" + "="*80) +print("检查 sensors_events 表的所有字段") +print("="*80) + +# 查看表结构 +try: + df = pd.read_sql("DESCRIBE sensors_events", engine) + print("\n表所有字段列表:") + print(df.to_string()) + + # 查找可能包含国家信息的字段 + country_keywords = ['country', '国家', 'geo', 'nation', '地区', 'region', 'location'] + print("\n" + "="*80) + print("可能包含国家/地区信息的字段:") + print("="*80) + + for field in df['Field'].values: + field_lower = field.lower() + for keyword in country_keywords: + if keyword in field_lower: + print(f" - {field}") + + # 特别检查一些可能的字段 + potential_fields = ['country', 'geo_country', 'user_country', 'ip_country', + 'location_country', 'browser_country', 'device_country'] + + print("\n" + "="*80) + print("检查常见国家字段名称:") + print("="*80) + + all_fields = df['Field'].values.tolist() + for field in potential_fields: + if field in all_fields: + print(f" ✓ 找到字段: {field}") + # 查询该字段的样本数据 + try: + sample_df = pd.read_sql(f"SELECT DISTINCT {field} FROM sensors_events WHERE {field} IS NOT NULL LIMIT 20", engine) + print(f" 样本值: {sample_df[field].tolist()}") + except: + pass + else: + print(f" ✗ 未找到: {field}") + + # 查看所有字段名称的列表(方便手动检查) + print("\n" + "="*80) + print("所有字段名称列表(用于手动检查):") + print("="*80) + for i, field in enumerate(all_fields, 1): + print(f"{i:3d}. {field}") + +except Exception as e: + print(f"无法获取表结构: {e}") + +print("\n" + "="*80) +print("检查完成") +print("="*80) diff --git a/offline_tasks/test/check_geo_info.py b/offline_tasks/test/check_geo_info.py new file mode 100644 index 0000000..1c4c84f --- /dev/null +++ b/offline_tasks/test/check_geo_info.py @@ -0,0 +1,144 @@ +""" +检查 sensors_events 表可能的地理位置信息 +""" +import sys +import os +sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +from db_service import create_db_connection +from offline_tasks.config.offline_config import DB_CONFIG +import pandas as pd +import json + +# 创建数据库连接 +print("连接数据库...") +engine = create_db_connection( + DB_CONFIG['host'], + DB_CONFIG['port'], + DB_CONFIG['database'], + DB_CONFIG['username'], + DB_CONFIG['password'] +) + +print("\n" + "="*80) +print("检查地理位置相关信息") +print("="*80) + +# 1. 检查浏览器语言 +print("\n1. 浏览器语言 (__browser_language):") +try: + df_lang = pd.read_sql(""" + SELECT __browser_language, COUNT(*) as count + FROM sensors_events + WHERE __browser_language IS NOT NULL + GROUP BY __browser_language + ORDER BY count DESC + LIMIT 20 + """, engine) + print(df_lang.to_string(index=False)) +except Exception as e: + print(f"查询失败: {e}") + +# 2. 检查 IP 地址 +print("\n2. IP地址样本 (ip):") +try: + df_ip = pd.read_sql(""" + SELECT DISTINCT ip + FROM sensors_events + WHERE ip IS NOT NULL + LIMIT 10 + """, engine) + print(df_ip['ip'].tolist()) +except Exception as e: + print(f"查询失败: {e}") + +# 3. 检查 __properties JSON字段中是否包含地理位置信息 +print("\n3. 检查 __properties 字段(可能包含地理位置):") +try: + df_props = pd.read_sql(""" + SELECT __properties + FROM sensors_events + WHERE __properties IS NOT NULL + LIMIT 5 + """, engine) + + print("\n样本数据(前5条):") + for i, prop in enumerate(df_props['__properties'].tolist(), 1): + print(f"\n第{i}条:") + if isinstance(prop, str): + try: + prop_json = json.loads(prop) + print(json.dumps(prop_json, indent=2, ensure_ascii=False)[:500]) + except: + print(prop[:200]) + else: + print(prop) +except Exception as e: + print(f"查询失败: {e}") + +# 4. 检查 __properties 中的所有键 +print("\n\n4. __properties 中的所有键名(查找地理位置相关):") +try: + df_props = pd.read_sql(""" + SELECT __properties + FROM sensors_events + WHERE __properties IS NOT NULL + LIMIT 100 + """, engine) + + # 收集所有键 + all_keys = set() + for prop in df_props['__properties'].tolist(): + if isinstance(prop, str): + try: + prop_json = json.loads(prop) + if isinstance(prop_json, dict): + all_keys.update(prop_json.keys()) + except: + pass + + print(f"\n找到 {len(all_keys)} 个不同的键:") + geo_keywords = ['country', 'geo', 'nation', '地区', '区域', 'city', 'province', 'state', 'location', 'region'] + + for key in sorted(all_keys): + is_geo = False + for keyword in geo_keywords: + if keyword.lower() in key.lower(): + is_geo = True + break + + if is_geo: + print(f" ★ {key} (可能是地理位置)") + else: + print(f" {key}") + +except Exception as e: + print(f"查询失败: {e}") + +# 5. 检查是否有其他可能的地理位置字段 +print("\n\n5. 检查其他可能包含地理位置的字段:") +try: + # 检查 channel_source 和 channel_type 是否包含地理位置信息 + df_geo = pd.read_sql(""" + SELECT channel_type, channel_source, COUNT(*) as count + FROM sensors_events + WHERE channel_type LIKE '%国家%' + OR channel_type LIKE '%地区%' + OR channel_source LIKE '%国家%' + OR channel_source LIKE '%地区%' + GROUP BY channel_type, channel_source + ORDER BY count DESC + LIMIT 20 + """, engine) + + if len(df_geo) > 0: + print(df_geo.to_string(index=False)) + else: + print("未找到包含国家/地区关键词的 channel_type 或 channel_source") + +except Exception as e: + print(f"查询失败: {e}") + +print("\n" + "="*80) +print("检查完成") +print("="*80) diff --git a/offline_tasks/test/query_browser_language.py b/offline_tasks/test/query_browser_language.py new file mode 100644 index 0000000..a26e1f9 --- /dev/null +++ b/offline_tasks/test/query_browser_language.py @@ -0,0 +1,166 @@ +""" +查询 __browser_language 字段的详细数据 +""" +import sys +import os +sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +from db_service import create_db_connection +from offline_tasks.config.offline_config import DB_CONFIG +import pandas as pd + +# 创建数据库连接 +print("连接数据库...") +engine = create_db_connection( + DB_CONFIG['host'], + DB_CONFIG['port'], + DB_CONFIG['database'], + DB_CONFIG['username'], + DB_CONFIG['password'] +) + +print("\n" + "="*80) +print("查询 __browser_language 字段数据") +print("="*80) + +# 1. 查看所有不同的浏览器语言及其数量 +print("\n1. 所有浏览器语言及其数量(按数量排序):") +try: + df = pd.read_sql(""" + SELECT + __browser_language, + COUNT(*) as count, + ROUND(COUNT(*) * 100.0 / (SELECT COUNT(*) FROM sensors_events WHERE __browser_language IS NOT NULL), 2) as percentage + FROM sensors_events + WHERE __browser_language IS NOT NULL + GROUP BY __browser_language + ORDER BY count DESC + """, engine) + + print(f"\n总共找到 {len(df)} 种不同的浏览器语言") + print(f"总记录数: {df['count'].sum():,}") + print("\n前50种语言:") + print(df.head(50).to_string(index=False)) + +except Exception as e: + print(f"查询失败: {e}") + +# 2. 查看样本数据(包含其他字段) +print("\n\n2. 样本数据(包含相关字段):") +try: + df_sample = pd.read_sql(""" + SELECT + __browser_language, + __os, + __browser, + client_platform, + business_platform, + create_time + FROM sensors_events + WHERE __browser_language IS NOT NULL + ORDER BY create_time DESC + LIMIT 30 + """, engine) + + print(df_sample.to_string(index=False)) + +except Exception as e: + print(f"查询失败: {e}") + +# 3. 按语言和平台分组统计 +print("\n\n3. 按语言和平台分组统计(Top 30):") +try: + df_platform = pd.read_sql(""" + SELECT + __browser_language, + client_platform, + COUNT(*) as count + FROM sensors_events + WHERE __browser_language IS NOT NULL + GROUP BY __browser_language, client_platform + ORDER BY count DESC + LIMIT 30 + """, engine) + + print(df_platform.to_string(index=False)) + +except Exception as e: + print(f"查询失败: {e}") + +# 4. 查看一些特殊或罕见的语言 +print("\n\n4. 罕见或特殊的浏览器语言(数量<1000):") +try: + df_rare = pd.read_sql(""" + SELECT + __browser_language, + COUNT(*) as count + FROM sensors_events + WHERE __browser_language IS NOT NULL + GROUP BY __browser_language + HAVING count < 1000 + ORDER BY count DESC + LIMIT 30 + """, engine) + + print(df_rare.to_string(index=False)) + +except Exception as e: + print(f"查询失败: {e}") + +# 5. 查看包含特殊字符的语言代码 +print("\n\n5. 包含特殊字符的语言代码:") +try: + df_special = pd.read_sql(""" + SELECT + __browser_language, + COUNT(*) as count + FROM sensors_events + WHERE __browser_language IS NOT NULL + AND (__browser_language LIKE '%-%' + OR __browser_language LIKE '%;%' + OR LENGTH(__browser_language) > 10) + GROUP BY __browser_language + ORDER BY count DESC + LIMIT 20 + """, engine) + + print(df_special.to_string(index=False)) + +except Exception as e: + print(f"查询失败: {e}") + +# 6. 语言代码解析示例 +print("\n\n6. 主要语言代码分布(按语言家族分类):") +try: + # 简单分类 + df_family = pd.read_sql(""" + SELECT + CASE + WHEN __browser_language LIKE 'zh%' THEN '中文 (Chinese)' + WHEN __browser_language LIKE 'en%' THEN '英语 (English)' + WHEN __browser_language LIKE 'ru%' THEN '俄语 (Russian)' + WHEN __browser_language LIKE 'es%' THEN '西班牙语 (Spanish)' + WHEN __browser_language LIKE 'fr%' THEN '法语 (French)' + WHEN __browser_language LIKE 'tr%' THEN '土耳其语 (Turkish)' + WHEN __browser_language LIKE 'bg%' THEN '保加利亚语 (Bulgarian)' + WHEN __browser_language LIKE 'it%' THEN '意大利语 (Italian)' + WHEN __browser_language LIKE 'ar%' THEN '阿拉伯语 (Arabic)' + WHEN __browser_language LIKE 'hr%' THEN '克罗地亚语 (Croatian)' + ELSE '其他语言' + END as language_family, + COUNT(*) as count, + ROUND(COUNT(*) * 100.0 / (SELECT COUNT(*) FROM sensors_events WHERE __browser_language IS NOT NULL), 2) as percentage + FROM sensors_events + WHERE __browser_language IS NOT NULL + GROUP BY language_family + ORDER BY count DESC + """, engine) + + print(df_family.to_string(index=False)) + +except Exception as e: + print(f"查询失败: {e}") + +print("\n" + "="*80) +print("查询完成") +print("="*80) diff --git a/offline_tasks/test/query_buy_buyer_data.py b/offline_tasks/test/query_buy_buyer_data.py new file mode 100644 index 0000000..23b1c81 --- /dev/null +++ b/offline_tasks/test/query_buy_buyer_data.py @@ -0,0 +1,90 @@ +#!/usr/bin/env python3 +"""查询 buy_buyer 表的示例数据""" + +import os +import pymysql +import sys +sys.path.append(os.path.dirname(os.path.abspath(__file__))) +from config.offline_config import DB_CONFIG + +def query_sample_data(): + """查询示例数据""" + 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: + # 查询指定字段的示例数据 + sql = """ + SELECT id, lang, customer_brand, countries, province, city, area, city_code + FROM buy_buyer + WHERE is_delete = 0 + LIMIT 20 + """ + cursor.execute(sql) + result = cursor.fetchall() + + # 获取列名 + columns = [desc[0] for desc in cursor.description] + + print("=" * 140) + print(f"{'ID':<15} {'语言':<10} {'客户品牌':<20} {'国家':<15} {'省份':<20} {'城市':<20} {'区域':<15} {'城市代码':<10}") + print("=" * 140) + + for row in result: + id_val = row[0] if row[0] is not None else '' + lang = row[1] if row[1] is not None else '' + brand = row[2] if row[2] is not None else '' + countries = row[3] if row[3] is not None else '' + province = row[4] if row[4] is not None else '' + city = row[5] if row[5] is not None else '' + area = row[6] if row[6] is not None else '' + city_code = row[7] if row[7] is not None else '' + + # 截断过长的字符串 + brand = (brand[:18] + '..') if len(brand) > 20 else brand + province = (province[:18] + '..') if len(province) > 20 else province + city = (city[:18] + '..') if len(city) > 20 else city + + print(f"{id_val:<15} {lang:<10} {brand:<20} {countries:<15} {province:<20} {city:<20} {area:<15} {city_code:<10}") + + print("=" * 140) + print(f"\n总计: {len(result)} 条记录") + + # 查询字段值分布统计 + print("\n" + "=" * 80) + print("字段值分布统计:") + print("=" * 80) + + stats_queries = [ + ("语言 (lang)", "SELECT lang, COUNT(*) as cnt FROM buy_buyer WHERE is_delete = 0 GROUP BY lang ORDER BY cnt DESC LIMIT 10"), + ("国家 (countries)", "SELECT countries, COUNT(*) as cnt FROM buy_buyer WHERE is_delete = 0 GROUP BY countries ORDER BY cnt DESC LIMIT 10"), + ("省份 (province)", "SELECT province, COUNT(*) as cnt FROM buy_buyer WHERE is_delete = 0 GROUP BY province ORDER BY cnt DESC LIMIT 10"), + ("城市 (city)", "SELECT city, COUNT(*) as cnt FROM buy_buyer WHERE is_delete = 0 GROUP BY city ORDER BY cnt DESC LIMIT 10"), + ("客户品牌 (customer_brand)", "SELECT customer_brand, COUNT(*) as cnt FROM buy_buyer WHERE is_delete = 0 GROUP BY customer_brand ORDER BY cnt DESC LIMIT 10"), + ] + + for title, query in stats_queries: + print(f"\n【{title}】") + cursor.execute(query) + stats = cursor.fetchall() + for row in stats: + value = row[0] if row[0] is not None else '(NULL)' + count = row[1] + print(f" {value:<30} {count:>10} 条") + + except Exception as e: + print(f"查询失败: {e}") + finally: + if 'connection' in locals(): + connection.close() + +if __name__ == "__main__": + query_sample_data() diff --git a/offline_tasks/test/query_buy_buyer_fields.py b/offline_tasks/test/query_buy_buyer_fields.py new file mode 100644 index 0000000..fc495f8 --- /dev/null +++ b/offline_tasks/test/query_buy_buyer_fields.py @@ -0,0 +1,53 @@ +#!/usr/bin/env python3 +"""查询 buy_buyer 表的字段信息""" + +import os +import pymysql +import sys +sys.path.append(os.path.dirname(os.path.abspath(__file__))) +from config.offline_config import DB_CONFIG + +def query_table_fields(): + """查询表结构""" + 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: + # 查询表结构 + sql = "DESCRIBE buy_buyer" + cursor.execute(sql) + result = cursor.fetchall() + + print("=" * 100) + print(f"{'字段名':<30} {'类型':<20} {'允许NULL':<10} {'键':<10} {'默认值':<15} {'额外信息'}") + print("=" * 100) + + for row in result: + field = row[0] + type_info = row[1] + null = row[2] + key = row[3] + default = row[4] + extra = row[5] + + print(f"{field:<30} {type_info:<20} {null:<10} {key:<10} {str(default):<15} {extra}") + + print("=" * 100) + print(f"\n总计: {len(result)} 个字段") + + except Exception as e: + print(f"查询失败: {e}") + finally: + if 'connection' in locals(): + connection.close() + +if __name__ == "__main__": + query_table_fields() diff --git a/offline_tasks/test/query_buyer_dict.py b/offline_tasks/test/query_buyer_dict.py new file mode 100644 index 0000000..a568416 --- /dev/null +++ b/offline_tasks/test/query_buyer_dict.py @@ -0,0 +1,122 @@ +#!/usr/bin/env python3 +"""查询客户类型字典的准确含义""" + +import os +import pymysql +import sys +sys.path.append(os.path.dirname(os.path.abspath(__file__))) +from config.offline_config import DB_CONFIG + +def query_buyer_type_dict(): + """查询客户类型字典""" + 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: + print("=" * 100) + print("查询客户类型相关的字典") + print("=" * 100) + + # 1. 查找所有与客户类型相关的字典类别 + print("\n【1. 查找客户类型相关的字典类别】") + sql = """ + SELECT code, name + FROM pub_dict_category + WHERE code LIKE '%buyer%' + OR code LIKE '%customer%' + OR code LIKE '%nature%' + OR code LIKE '%company%' + OR code LIKE '%cooperate%' + ORDER BY code + """ + cursor.execute(sql) + categories = cursor.fetchall() + + if categories: + print(f"\n找到 {len(categories)} 个相关字典类别:") + for cat in categories: + print(f" - {cat[0]:<30} {cat[1]}") + else: + print("\n未找到完全匹配的字典,显示所有类别:") + sql = "SELECT code, name FROM pub_dict_category ORDER BY sort_order LIMIT 50" + cursor.execute(sql) + all_cats = cursor.fetchall() + for cat in all_cats: + print(f" - {cat[0]:<30} {cat[1]}") + + # 2. 针对可能相关的字典类别查询具体值 + print("\n" + "=" * 100) + print("【2. 查询可能相关的字典值】") + + possible_codes = [ + 'supplier_nature', # 公司性质 + 'supplier_type', # 供应商类别 + 'customer_type', # 客户类型 + 'buyer_from', # 买家来源 + 'cooperate_type' # 合作类型 + ] + + for dict_code in possible_codes: + print(f"\n--- 字典: {dict_code} ---") + + # 查询该类别下的所有条目 + sql = """ + SELECT i.id, i.code, i.name, i.sort_order, il.lang, il.name as lang_name + FROM pub_dict_item i + LEFT JOIN pub_dict_item_lang il ON i.id = il.dict_item_id + WHERE i.category_code = %s + ORDER BY i.sort_order, i.id + """ + cursor.execute(sql, (dict_code,)) + items = cursor.fetchall() + + if items: + print(f"{'code':<15} {'name':<30} {'sort':<10} {'lang':<10} {'翻译名称'}") + print("-" * 100) + for item in items: + code = item[1] if item[1] else 'NULL' + name = item[2] if item[2] else 'NULL' + sort = item[3] if item[3] else 'NULL' + lang = item[4] if item[4] else 'NULL' + lang_name = item[5] if item[5] else '' + + # 只显示主要语言和翻译 + if lang in ['zh', 'en', 'ru', None]: + print(f"{code:<15} {name:<30} {sort:<10} {lang if lang else 'NULL':<10} {lang_name}") + else: + print(" (该字典不存在或无数据)") + + # 3. 查询所有字典类别 + print("\n" + "=" * 100) + print("【3. 所有可用的字典类别(前50个)】") + sql = """ + SELECT code, name + FROM pub_dict_category + ORDER BY sort_order + LIMIT 50 + """ + cursor.execute(sql) + all_cats = cursor.fetchall() + + print(f"{'代码':<30} {'名称'}") + print("-" * 60) + for cat in all_cats: + print(f"{cat[0]:<30} {cat[1]}") + + except Exception as e: + print(f"查询失败: {e}") + import traceback + traceback.print_exc() + finally: + if 'connection' in locals(): + connection.close() + +if __name__ == "__main__": + query_buyer_type_dict() diff --git a/offline_tasks/test/query_buyer_type_detail.py b/offline_tasks/test/query_buyer_type_detail.py new file mode 100644 index 0000000..f75356b --- /dev/null +++ b/offline_tasks/test/query_buyer_type_detail.py @@ -0,0 +1,186 @@ +#!/usr/bin/env python3 +"""查询 buy_buyer 表客户类型字段的详细信息""" + +import os +import pymysql +import sys +sys.path.append(os.path.dirname(os.path.abspath(__file__))) +from config.offline_config import DB_CONFIG + +def query_buyer_type_details(): + """查询客户类型详细信息""" + 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: + print("=" * 100) + print("客户类型字段详细分析") + print("=" * 100) + + # 1. customer_type 字段 + print("\n【1. customer_type 字段】") + sql = """ + SELECT customer_type, COUNT(*) as count + FROM buy_buyer + WHERE is_delete = 0 + GROUP BY customer_type + ORDER BY customer_type + """ + cursor.execute(sql) + result = cursor.fetchall() + + print(f"{'customer_type':<20} {'买家数量':>15}") + print("-" * 50) + for row in result: + val = row[0] if row[0] is not None else 'NULL' + count = row[1] + print(f"{val:<20} {count:>15,}") + + # 查询不同 customer_type 的示例 + print("\n示例买家名称:") + for ctype in [1, 2]: + sql = """ + SELECT id, name, customer_type, countries + FROM buy_buyer + WHERE customer_type = %s AND is_delete = 0 + LIMIT 5 + """ + cursor.execute(sql, (ctype,)) + samples = cursor.fetchall() + if samples: + print(f"\n customer_type={ctype} 的示例:") + for s in samples: + print(f" - [{s[0]}] {s[1]} (国家:{s[3]})") + + # 2. buyer_from 字段 + print("\n" + "=" * 100) + print("【2. buyer_from 字段】") + sql = """ + SELECT buyer_from, COUNT(*) as count + FROM buy_buyer + WHERE is_delete = 0 + GROUP BY buyer_from + ORDER BY buyer_from + """ + cursor.execute(sql) + result = cursor.fetchall() + + print(f"{'buyer_from':<20} {'买家数量':>15}") + print("-" * 50) + for row in result: + val = row[0] if row[0] is not None else 'NULL' + count = row[1] + print(f"{val:<20} {count:>15,}") + + # 查询不同 buyer_from 的示例 + print("\n示例买家名称:") + for bfrom in [1, 2, 3, 4, 5, 6, 10, 11, 12]: + sql = """ + SELECT id, name, buyer_from, countries + FROM buy_buyer + WHERE buyer_from = %s AND is_delete = 0 + LIMIT 3 + """ + cursor.execute(sql, (bfrom,)) + samples = cursor.fetchall() + if samples: + print(f"\n buyer_from={bfrom} 的示例:") + for s in samples: + print(f" - [{s[0]}] {s[1]} (国家:{s[3]})") + + # 3. nature_of_company 字段 + print("\n" + "=" * 100) + print("【3. nature_of_company 字段(公司性质)】") + sql = """ + SELECT nature_of_company, COUNT(*) as count + FROM buy_buyer + WHERE is_delete = 0 + GROUP BY nature_of_company + ORDER BY nature_of_company + """ + cursor.execute(sql) + result = cursor.fetchall() + + print(f"{'nature_of_company':<20} {'买家数量':>15}") + print("-" * 50) + for row in result: + val = row[0] if row[0] is not None else 'NULL' + count = row[1] + print(f"{val:<20} {count:>15,}") + + # 查询不同 nature_of_company 的示例 + print("\n示例买家名称:") + for nature in [51, 52]: + sql = """ + SELECT id, name, nature_of_company, countries + FROM buy_buyer + WHERE nature_of_company = %s AND is_delete = 0 + LIMIT 5 + """ + cursor.execute(sql, (nature,)) + samples = cursor.fetchall() + if samples: + print(f"\n nature_of_company={nature} 的示例:") + for s in samples: + print(f" - [{s[0]}] {s[1]} (国家:{s[3]})") + + # 4. 查找是否有数据字典表 + print("\n" + "=" * 100) + print("【查找数据字典表】") + sql = """ + SHOW TABLES LIKE '%dict%' + """ + cursor.execute(sql) + dict_tables = cursor.fetchall() + + if dict_tables: + print("\n找到以下字典表:") + for table in dict_tables: + print(f" - {table[0]}") + else: + print("\n未找到包含 'dict' 关键字的表") + + # 5. 组合查询 - 看看这些字段的关系 + print("\n" + "=" * 100) + print("【客户类型字段组合分布】") + sql = """ + SELECT + customer_type, + buyer_from, + nature_of_company, + COUNT(*) as count + FROM buy_buyer + WHERE is_delete = 0 + GROUP BY customer_type, buyer_from, nature_of_company + ORDER BY count DESC + LIMIT 20 + """ + cursor.execute(sql) + result = cursor.fetchall() + + print(f"{'customer_type':<15} {'buyer_from':<15} {'nature_of_company':<20} {'数量':>10}") + print("-" * 80) + for row in result: + ct = row[0] if row[0] is not None else 'NULL' + bf = row[1] if row[1] is not None else 'NULL' + nc = row[2] if row[2] is not None else 'NULL' + count = row[3] + print(f"{ct:<15} {bf:<15} {nc:<20} {count:>10,}") + + except Exception as e: + print(f"查询失败: {e}") + import traceback + traceback.print_exc() + finally: + if 'connection' in locals(): + connection.close() + +if __name__ == "__main__": + query_buyer_type_details() diff --git a/offline_tasks/test/query_buyer_type_final.py b/offline_tasks/test/query_buyer_type_final.py new file mode 100644 index 0000000..f7286b6 --- /dev/null +++ b/offline_tasks/test/query_buyer_type_final.py @@ -0,0 +1,186 @@ +#!/usr/bin/env python3 +"""查询 buy_buyer_type 采购商分类字典""" + +import os +import pymysql +import sys +sys.path.append(os.path.dirname(os.path.abspath(__file__))) +from config.offline_config import DB_CONFIG + +def query_buyer_type(): + """查询采购商分类字典""" + 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: + print("=" * 100) + print("【buy_buyer_type - 采购商分类】") + print("=" * 100) + + sql = """ + SELECT i.id, i.code, i.name, i.sort_order, il.lang, il.name as lang_name + FROM pub_dict_item i + LEFT JOIN pub_dict_item_lang il ON i.id = il.dict_item_id + WHERE i.category_code = 'buy_buyer_type' + ORDER BY i.sort_order, i.id, il.lang + """ + cursor.execute(sql) + items = cursor.fetchall() + + if items: + print(f"{'code':<10} {'name(zh)':<40} {'name(en/ru)':<40} {'sort':<10}") + print("-" * 120) + + current_code = None + zh_name = None + + for item in items: + code = item[1] if item[1] else 'NULL' + name = item[2] if item[2] else 'NULL' + sort = item[3] if item[3] else 'NULL' + lang = item[4] if item[4] else 'NULL' + lang_name = item[5] if item[5] else 'NULL' + + if code != current_code: + if current_code is not None: + print(f"{current_code:<10} {zh_name:<40} {other_langs:<40} {sort:<10}") + current_code = code + zh_name = name if lang == 'zh' else name + other_langs = '' + + if lang != 'zh': + other_langs += f"{lang}:{lang_name} " if lang_name else '' + + # 打印最后一项 + if current_code is not None: + print(f"{current_code:<10} {zh_name:<40} {other_langs:<40} {sort:<10}") + + # 2. 查询 buyer_from 的所有值(包括6, 10, 11, 12) + print("\n" + "=" * 100) + print("【buyer_from - 采购商来源】") + print("=" * 100) + + sql = """ + SELECT i.id, i.code, i.name, i.sort_order, il.lang, il.name as lang_name + FROM pub_dict_item i + LEFT JOIN pub_dict_item_lang il ON i.id = il.dict_item_id + WHERE i.category_code = 'buyer_from' + ORDER BY i.sort_order, i.id, il.lang + """ + cursor.execute(sql) + items = cursor.fetchall() + + if items: + print(f"{'code':<10} {'name':<30} {'sort':<10}") + print("-" * 60) + + for item in items: + code = item[1] if item[1] else 'NULL' + name = item[2] if item[2] else 'NULL' + sort = item[3] if item[3] else 'NULL' + lang = item[4] if item[4] else 'NULL' + + if lang in ['zh', None]: + print(f"{code:<10} {name:<30} {sort:<10}") + + # 3. 查询 buyer_nature (公司性质) + print("\n" + "=" * 100) + print("【buyer_nature - 公司性质】") + print("=" * 100) + + sql = """ + SELECT i.id, i.code, i.name, i.sort_order, il.lang, il.name as lang_name + FROM pub_dict_item i + LEFT JOIN pub_dict_item_lang il ON i.id = il.dict_item_id + WHERE i.category_code = 'buyer_nature' + ORDER BY i.sort_order, i.id, il.lang + """ + cursor.execute(sql) + items = cursor.fetchall() + + if items: + print(f"{'code':<10} {'name':<50} {'sort':<10}") + print("-" * 80) + + for item in items: + code = item[1] if item[1] else 'NULL' + name = item[2] if item[2] else 'NULL' + sort = item[3] if item[3] else 'NULL' + lang = item[4] if item[4] else 'NULL' + + if lang in ['zh', None]: + print(f"{code:<10} {name:<50} {sort:<10}") + + # 4. 查询 nature_of_company + print("\n" + "=" * 100) + print("【nature_of_company - 公司类型】") + print("=" * 100) + + sql = """ + SELECT i.id, i.code, i.name, i.sort_order, il.lang, il.name as lang_name + FROM pub_dict_item i + LEFT JOIN pub_dict_item_lang il ON i.id = il.dict_item_id + WHERE i.category_code = 'nature_of_company' + ORDER BY i.sort_order, i.id, il.lang + """ + cursor.execute(sql) + items = cursor.fetchall() + + if items: + print(f"{'code':<10} {'name':<50} {'sort':<10}") + print("-" * 80) + + for item in items: + code = item[1] if item[1] else 'NULL' + name = item[2] if item[2] else 'NULL' + sort = item[3] if item[3] else 'NULL' + lang = item[4] if item[4] else 'NULL' + + if lang in ['zh', None]: + print(f"{code:<10} {name:<50} {sort:<10}") + + # 5. 实际数据验证 + print("\n" + "=" * 120) + print("【实际数据验证 - 查询 buy_buyer 表中的客户类型分布】") + print("=" * 120) + + # 尝试不同的客户类型字段 + type_fields = ['customer_type', 'buyer_from', 'nature_of_company', 'cooperate_type'] + + for field in type_fields: + print(f"\n--- {field} 字段分布 ---") + sql = f""" + SELECT {field}, COUNT(*) as count + FROM buy_buyer + WHERE is_delete = 0 + GROUP BY {field} + ORDER BY count DESC + """ + cursor.execute(sql) + result = cursor.fetchall() + + if result: + print(f"{'值':<10} {'数量':>10}") + print("-" * 30) + for row in result[:10]: + val = str(row[0]) if row[0] is not None else 'NULL' + count = row[1] + print(f"{val:<10} {count:>10,}") + + except Exception as e: + print(f"查询失败: {e}") + import traceback + traceback.print_exc() + finally: + if 'connection' in locals(): + connection.close() + +if __name__ == "__main__": + query_buyer_type() diff --git a/offline_tasks/test/query_customer_type_field.py b/offline_tasks/test/query_customer_type_field.py new file mode 100644 index 0000000..b601be0 --- /dev/null +++ b/offline_tasks/test/query_customer_type_field.py @@ -0,0 +1,139 @@ +#!/usr/bin/env python3 +"""查询 buy_buyer 表的客户类型字段""" + +import os +import pymysql +import sys +sys.path.append(os.path.dirname(os.path.abspath(__file__))) +from config.offline_config import DB_CONFIG + +def query_customer_type_fields(): + """查询客户类型相关字段""" + 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: + # 先获取所有字段名 + cursor.execute("DESCRIBE buy_buyer") + all_fields = [row[0] for row in cursor.fetchall()] + + print("=" * 80) + print("可能包含客户类型信息的字段") + print("=" * 80) + + # 查找可能包含类型信息的字段 + type_keywords = ['type', 'category', 'class', 'nature', 'customer'] + relevant_fields = [] + + for field in all_fields: + field_lower = field.lower() + for keyword in type_keywords: + if keyword in field_lower: + relevant_fields.append(field) + break + + for field in relevant_fields: + print(f" - {field}") + + # 重点查询几个可能的字段 + priority_fields = [ + 'customer_type', + 'buyer_from', + 'nature_of_company', + 'cooperate_type', + 'price_level', + 'maturity', + 'status' + ] + + print("\n" + "=" * 100) + print("关键字段的值分布分析") + print("=" * 100) + + for field_name in priority_fields: + if field_name in all_fields: + print(f"\n【{field_name}】") + sql = f""" + SELECT {field_name}, COUNT(*) as count + FROM buy_buyer + WHERE is_delete = 0 AND {field_name} IS NOT NULL + GROUP BY {field_name} + ORDER BY count DESC + LIMIT 15 + """ + + try: + cursor.execute(sql) + result = cursor.fetchall() + + if result: + for row in result: + value = row[0] if row[0] else '(NULL)' + count = row[1] + # 截断过长的值 + if isinstance(value, str) and len(value) > 30: + value = value[:27] + '...' + print(f" {value:<35} {count:>10,} 条") + else: + print(f" (无数据或全为NULL)") + + except Exception as e: + print(f" 查询失败: {e}") + + # 查询包含客户类型信息的完整记录示例 + print("\n" + "=" * 140) + print("包含客户类型字段的完整记录示例") + print("=" * 140) + + valid_fields = [f for f in priority_fields if f in all_fields] + select_fields = ['id', 'name', 'customer_type', 'buyer_from', + 'nature_of_company', 'cooperate_type', 'price_level'] + + # 只选择存在的字段 + final_fields = [f for f in select_fields if f in all_fields] + + sql = f""" + SELECT {', '.join(final_fields)} + FROM buy_buyer + WHERE is_delete = 0 + LIMIT 20 + """ + + cursor.execute(sql) + samples = cursor.fetchall() + + # 打印表头 + header = " | ".join([f"{field:<20}" for field in final_fields]) + print(header) + print("-" * len(header)) + + # 打印数据 + for sample in samples: + row_data = [] + for val in sample: + if val is None: + row_data.append(f"{'NULL':<20}") + elif isinstance(val, str): + val_str = (val[:17] + '..') if len(val) > 20 else val + row_data.append(f"{val_str:<20}") + else: + row_data.append(f"{str(val):<20}") + print(" | ".join(row_data)) + + except Exception as e: + print(f"查询失败: {e}") + import traceback + traceback.print_exc() + finally: + if 'connection' in locals(): + connection.close() + +if __name__ == "__main__": + query_customer_type_fields() diff --git a/offline_tasks/test/query_customer_type_values.py b/offline_tasks/test/query_customer_type_values.py new file mode 100644 index 0000000..100f5c8 --- /dev/null +++ b/offline_tasks/test/query_customer_type_values.py @@ -0,0 +1,230 @@ +#!/usr/bin/env python3 +"""查询 customer_type 字段的具体值""" + +import os +import pymysql +import sys +sys.path.append(os.path.dirname(os.path.abspath(__file__))) +from config.offline_config import DB_CONFIG + +def query_customer_type_values(): + """查询 customer_type 的具体值""" + 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: + print("=" * 140) + print(" customer_type 字段详细分析") + print("=" * 140) + + # 1. 查询 customer_type 的统计分布 + print("\n【1. customer_type 字段分布统计】") + sql = """ + SELECT customer_type, COUNT(*) as count, + ROUND(COUNT(*) * 100.0 / SUM(COUNT(*)) OVER(), 2) as percentage + FROM buy_buyer + WHERE is_delete = 0 + GROUP BY customer_type + ORDER BY customer_type + """ + cursor.execute(sql) + result = cursor.fetchall() + + print(f"{'customer_type':<20} {'买家数量':>12} {'占比':>10}") + print("-" * 60) + total = 0 + for row in result: + val = str(row[0]) if row[0] is not None else 'NULL' + count = row[1] + percentage = row[2] + total += count + print(f"{val:<20} {count:>12,} {percentage:>10}%") + + print("-" * 60) + print(f"{'总计':<20} {total:>12,}") + + # 2. 查询 customer_type=1 的详细示例 + print("\n" + "=" * 140) + print("【2. customer_type = 1 的买家示例(前30个)】") + sql = """ + SELECT id, name, customer_type, countries, lang, + main_category, nature_of_company, buyer_from + FROM buy_buyer + WHERE customer_type = 1 AND is_delete = 0 + ORDER BY id + LIMIT 30 + """ + cursor.execute(sql) + result = cursor.fetchall() + + if result: + print(f"{'ID':<10} {'买家名称':<35} {'国家':<8} {'语言':<6} {'主营类目':<30} {'公司性质':<15} {'来源':<10}") + print("-" * 140) + + for row in result: + id_val = str(row[0]) + name = (row[1][:32] + '..') if row[1] and len(row[1]) > 35 else (row[1] if row[1] else '') + countries = str(row[3]) if row[3] else '' + lang = str(row[4]) if row[4] else '' + main_category = (row[5][:27] + '..') if row[5] and len(row[5]) > 30 else (row[5] if row[5] else '') + nature = str(row[6]) if row[6] else '' + buyer_from = str(row[7]) if row[7] else '' + + print(f"{id_val:<10} {name:<35} {countries:<8} {lang:<6} {main_category:<30} {nature:<15} {buyer_from:<10}") + else: + print(" (无数据)") + + # 3. 查询 customer_type=2 的详细示例 + print("\n" + "=" * 140) + print("【3. customer_type = 2 的买家示例(全部)】") + sql = """ + SELECT id, name, customer_type, countries, lang, + main_category, nature_of_company, buyer_from + FROM buy_buyer + WHERE customer_type = 2 AND is_delete = 0 + ORDER BY id + """ + cursor.execute(sql) + result = cursor.fetchall() + + if result: + print(f"{'ID':<10} {'买家名称':<35} {'国家':<8} {'语言':<6} {'主营类目':<30} {'公司性质':<15} {'来源':<10}") + print("-" * 140) + + for row in result: + id_val = str(row[0]) + name = (row[1][:32] + '..') if row[1] and len(row[1]) > 35 else (row[1] if row[1] else '') + countries = str(row[3]) if row[3] else '' + lang = str(row[4]) if row[4] else '' + main_category = (row[5][:27] + '..') if row[5] and len(row[5]) > 30 else (row[5] if row[5] else '') + nature = str(row[6]) if row[6] else '' + buyer_from = str(row[7]) if row[7] else '' + + print(f"{id_val:<10} {name:<35} {countries:<8} {lang:<6} {main_category:<30} {nature:<15} {buyer_from:<10}") + else: + print(" (无数据)") + + # 4. 分析 customer_type 与其他字段的关联 + print("\n" + "=" * 140) + print("【4. customer_type 与其他字段的关联分析】") + + # 与国家分布 + print("\n 4.1 按国家分布:") + sql = """ + SELECT customer_type, countries, COUNT(*) as count + FROM buy_buyer + WHERE customer_type IS NOT NULL AND is_delete = 0 + GROUP BY customer_type, countries + ORDER BY customer_type, count DESC + """ + cursor.execute(sql) + result = cursor.fetchall() + + current_type = None + for row in result: + ctype = row[0] + country = row[1] if row[1] else 'NULL' + count = row[2] + + if ctype != current_type: + print(f"\n customer_type = {ctype}:") + current_type = ctype + + print(f" - 国家{country}: {count} 个买家") + + # 与公司性质关联 + print("\n 4.2 与 nature_of_company 关联:") + sql = """ + SELECT customer_type, nature_of_company, COUNT(*) as count + FROM buy_buyer + WHERE customer_type IS NOT NULL AND is_delete = 0 + GROUP BY customer_type, nature_of_company + ORDER BY customer_type, nature_of_company + """ + cursor.execute(sql) + result = cursor.fetchall() + + for row in result: + ctype = row[0] + nature = row[1] if row[1] is not None else 'NULL' + count = row[2] + print(f" - customer_type={ctype}, nature_of_company={nature}: {count} 个买家") + + # 与来源关联 + print("\n 4.3 与 buyer_from 关联:") + sql = """ + SELECT customer_type, buyer_from, COUNT(*) as count + FROM buy_buyer + WHERE customer_type IS NOT NULL AND is_delete = 0 + GROUP BY customer_type, buyer_from + ORDER BY customer_type, buyer_from + """ + cursor.execute(sql) + result = cursor.fetchall() + + for row in result: + ctype = row[0] + bfrom = row[1] if row[1] is not None else 'NULL' + count = row[2] + print(f" - customer_type={ctype}, buyer_from={bfrom}: {count} 个买家") + + # 5. 查询是否有 customer_type 的字典定义 + print("\n" + "=" * 140) + print("【5. 查找 customer_type 的字典定义】") + + sql = """ + SELECT i.code, i.name, il.lang, il.name as lang_name + FROM pub_dict_item i + LEFT JOIN pub_dict_item_lang il ON i.id = il.dict_item_id + WHERE i.category_code = 'customer_type' + ORDER BY i.sort_order, i.code, il.lang + """ + cursor.execute(sql) + dict_result = cursor.fetchall() + + if dict_result: + print(f"\n找到 customer_type 字典定义:") + print(f"{'code':<10} {'name':<30} {'lang':<10} {'翻译名称'}") + print("-" * 80) + for row in dict_result: + code = str(row[0]) if row[0] else 'NULL' + name = row[1] if row[1] else 'NULL' + lang = row[2] if row[2] else 'NULL' + lang_name = row[3] if row[3] else '' + + if lang in ['zh', 'en', 'ru', None]: + print(f"{code:<10} {name:<30} {lang if lang else 'NULL':<10} {lang_name}") + else: + print("\n未找到 customer_type 字典定义") + print("\n尝试查找相关字典...") + sql = """ + SELECT code, name + FROM pub_dict_category + WHERE code LIKE '%customer%' OR code LIKE '%type%' + ORDER BY code + """ + cursor.execute(sql) + categories = cursor.fetchall() + + if categories: + print("\n找到相关字典类别:") + for cat in categories: + print(f" - {cat[0]}: {cat[1]}") + + except Exception as e: + print(f"查询失败: {e}") + import traceback + traceback.print_exc() + finally: + if 'connection' in locals(): + connection.close() + +if __name__ == "__main__": + query_customer_type_values() diff --git a/offline_tasks/test/query_dict_meaning.py b/offline_tasks/test/query_dict_meaning.py new file mode 100644 index 0000000..800be10 --- /dev/null +++ b/offline_tasks/test/query_dict_meaning.py @@ -0,0 +1,140 @@ +#!/usr/bin/env python3 +"""查询字典表获取客户类型代码的含义""" + +import os +import pymysql +import sys +sys.path.append(os.path.dirname(os.path.abspath(__file__))) +from config.offline_config import DB_CONFIG + +def query_dict_meanings(): + """查询字典表中的代码含义""" + 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: + print("=" * 100) + print("字典表结构分析") + print("=" * 100) + + # 查看字典表结构 + for table in ['pub_dict_item', 'pub_dict_item_lang']: + print(f"\n【{table} 表结构】") + sql = f"DESCRIBE {table}" + cursor.execute(sql) + result = cursor.fetchall() + + for row in result: + print(f" {row[0]:<30} {row[1]:<20}") + + # 查询 pub_dict_category + print("\n" + "=" * 100) + print("【pub_dict_category 表内容】") + sql = "SELECT * FROM pub_dict_category LIMIT 20" + cursor.execute(sql) + result = cursor.fetchall() + + cursor.execute("DESCRIBE pub_dict_category") + columns = [row[0] for row in cursor.fetchall()] + + print(f"{' | '.join(columns)}") + print("-" * 100) + for row in result: + print(" | ".join([str(v) if v is not None else 'NULL' for v in row])) + + # 查询 pub_dict_item 中与客户类型相关的条目 + print("\n" + "=" * 100) + print("【pub_dict_item 表内容 - 查找客户类型相关的字典】") + sql = """ + SELECT * FROM pub_dict_item + WHERE dict_code LIKE '%customer%' + OR dict_code LIKE '%buyer%' + OR dict_code LIKE '%type%' + OR dict_code LIKE '%nature%' + OR dict_code LIKE '%from%' + LIMIT 20 + """ + cursor.execute(sql) + result = cursor.fetchall() + + if result: + cursor.execute("DESCRIBE pub_dict_item") + columns = [row[0] for row in cursor.fetchall()] + + print(f"\n找到 {len(result)} 条相关字典") + print(f"{' | '.join(columns)}") + print("-" * 140) + for row in result: + print(" | ".join([str(v) if v is not None else 'NULL' for v in row])) + else: + print("未找到相关字典,显示所有字典类别:") + sql = "SELECT DISTINCT dict_code FROM pub_dict_item LIMIT 30" + cursor.execute(sql) + all_dicts = cursor.fetchall() + + for d in all_dicts: + print(f" - {d[0]}") + + # 查询 pub_dict_item_lang 获取具体值 + print("\n" + "=" * 100) + print("【pub_dict_item_lang 表内容 - 客户类型值查询】") + + # 尝试查询几个常见的字典代码 + possible_codes = ['customer_type', 'buyer_from', 'nature_of_company', 'cooperate_type'] + + for dict_code in possible_codes: + print(f"\n--- 查询字典: {dict_code} ---") + sql = """ + SELECT i.*, il.item_name, il.lang + FROM pub_dict_item i + LEFT JOIN pub_dict_item_lang il ON i.id = il.dict_item_id + WHERE i.dict_code = %s + ORDER BY i.item_value + """ + cursor.execute(sql, (dict_code,)) + result = cursor.fetchall() + + if result: + print(f"{'item_value':<15} {'item_code':<20} {'item_name':<30} {'lang':<10}") + print("-" * 80) + for row in result: + item_value = str(row[3]) if row[3] is not None else 'NULL' + item_code = str(row[2]) if row[2] is not None else 'NULL' + item_name = row[7] if row[7] is not None else 'NULL' + lang = row[8] if row[8] is not None else 'NULL' + print(f"{item_value:<15} {item_code:<20} {item_name:<30} {lang:<10}") + else: + print(" (未找到)") + + # 如果上述都没找到,显示所有字典代码 + print("\n" + "=" * 100) + print("【所有可用的字典代码】") + sql = """ + SELECT DISTINCT dict_code + FROM pub_dict_item + ORDER BY dict_code + """ + cursor.execute(sql) + all_dict_codes = cursor.fetchall() + + print(f"总共 {len(all_dict_codes)} 个字典:") + for i, d in enumerate(all_dict_codes, 1): + print(f" {i:3}. {d[0]}") + + except Exception as e: + print(f"查询失败: {e}") + import traceback + traceback.print_exc() + finally: + if 'connection' in locals(): + connection.close() + +if __name__ == "__main__": + query_dict_meanings() diff --git a/offline_tasks/test/query_geo_codes.py b/offline_tasks/test/query_geo_codes.py new file mode 100644 index 0000000..68755c6 --- /dev/null +++ b/offline_tasks/test/query_geo_codes.py @@ -0,0 +1,132 @@ +#!/usr/bin/env python3 +"""查询地理代码的含义""" + +import os +import pymysql +import sys +sys.path.append(os.path.dirname(os.path.abspath(__file__))) +from config.offline_config import DB_CONFIG + +def query_geo_info(): + """查询地理代码相关信息""" + 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: + print("=" * 100) + print("国家代码示例 (countries 字段)") + print("=" * 100) + + # 查询不同国家代码的示例 + sql = """ + SELECT + countries, + COUNT(*) as count + FROM buy_buyer + WHERE is_delete = 0 AND countries IS NOT NULL + GROUP BY countries + ORDER BY count DESC + LIMIT 15 + """ + cursor.execute(sql) + result = cursor.fetchall() + + for row in result: + country_code = row[0] + count = row[1] + print(f"国家代码 {country_code:<6} | 买家数量: {count:>6}") + + print("\n" + "=" * 100) + print("有地理信息的完整记录示例") + print("=" * 100) + + # 查询有完整地理信息的记录 + sql = """ + SELECT id, lang, customer_brand, + countries, province, city, area, city_code, + address_city_code, address_city_name + FROM buy_buyer + WHERE is_delete = 0 + AND countries IS NOT NULL + AND province IS NOT NULL + LIMIT 15 + """ + cursor.execute(sql) + result = cursor.fetchall() + + print(f"{'ID':<10} {'语言':<8} {'国家':<8} {'省份':<10} {'城市':<15} {'区域':<10} {'城市代码':<12} {'地址城市代码':<15} {'地址城市名称'}") + print("-" * 140) + + for row in result: + id_val = str(row[0]) + lang = row[1] if row[1] else '' + brand = row[2][:12] + '..' if row[2] and len(row[2]) > 15 else (row[2] if row[2] else '') + countries = str(row[3]) if row[3] is not None else '' + province = str(row[4]) if row[4] is not None else '' + city = str(row[5])[:12] if row[5] else '' + area = str(row[6]) if row[6] is not None else '' + city_code = str(row[7]) if row[7] is not None else '' + addr_city_code = str(row[8]) if row[8] is not None else '' + addr_city_name = str(row[9])[:15] if row[9] else '' + + print(f"{id_val:<10} {lang:<8} {countries:<8} {province:<10} {city:<15} {area:<10} {city_code:<12} {addr_city_code:<15} {addr_city_name}") + + print("\n" + "=" * 100) + print("城市代码 (city_code) 字段分析") + print("=" * 100) + + sql = """ + SELECT city_code, COUNT(*) as count, countries + FROM buy_buyer + WHERE is_delete = 0 AND city_code IS NOT NULL AND city_code != '' + GROUP BY city_code, countries + ORDER BY count DESC + LIMIT 15 + """ + cursor.execute(sql) + result = cursor.fetchall() + + for row in result: + city_code = row[0] + count = row[1] + countries = row[2] + print(f"城市代码: {city_code:<12} | 数量: {count:>6} | 国家代码: {countries}") + + print("\n" + "=" * 100) + print("地址城市代码 (address_city_code) 字段分析") + print("=" * 100) + + sql = """ + SELECT address_city_code, address_city_name, COUNT(*) as count + FROM buy_buyer + WHERE is_delete = 0 AND address_city_code IS NOT NULL AND address_city_code != '' + GROUP BY address_city_code, address_city_name + ORDER BY count DESC + LIMIT 15 + """ + cursor.execute(sql) + result = cursor.fetchall() + + for row in result: + city_code = row[0] + city_name = row[1] if row[1] else '' + count = row[2] + print(f"代码: {city_code:<12} | 名称: {city_name:<30} | 数量: {count:>6}") + + except Exception as e: + print(f"查询失败: {e}") + import traceback + traceback.print_exc() + finally: + if 'connection' in locals(): + connection.close() + +if __name__ == "__main__": + query_geo_info() diff --git a/offline_tasks/test/query_sensors_client_platform.py b/offline_tasks/test/query_sensors_client_platform.py new file mode 100644 index 0000000..cfe12bc --- /dev/null +++ b/offline_tasks/test/query_sensors_client_platform.py @@ -0,0 +1,140 @@ +#!/usr/bin/env python3 +"""查询 sensors_events 表的 client_platform 字段值""" + +import os +import pymysql +import sys +sys.path.append(os.path.dirname(os.path.abspath(__file__))) +from config.offline_config import DB_CONFIG + +def query_client_platform(): + """查询 client_platform 字段值分布""" + 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: + print("=" * 80) + print("sensors_events 表的 client_platform 字段值分布") + print("=" * 80) + + # 查询 client_platform 的分布情况 + sql = """ + SELECT + client_platform, + COUNT(*) as count, + ROUND(COUNT(*) * 100.0 / SUM(COUNT(*)) OVER(), 2) as percentage + FROM sensors_events + WHERE client_platform IS NOT NULL + GROUP BY client_platform + ORDER BY count DESC + """ + + cursor.execute(sql) + result = cursor.fetchall() + + print(f"{'client_platform':<30} {'数量':>15} {'占比':>10}") + print("-" * 80) + + total_count = 0 + for row in result: + platform = row[0] if row[0] else '(NULL)' + count = row[1] + percentage = row[2] + total_count += count + + print(f"{platform:<30} {count:>15,} {percentage:>10}%") + + print("-" * 80) + print(f"{'总计':<30} {total_count:>15,}") + + # 查询一些示例记录 + print("\n" + "=" * 100) + print("示例记录(包含 client_platform 相关字段)") + print("=" * 100) + + sql_sample = """ + SELECT + id, + client_platform, + platform, + browser, + browser_language, + device_id, + event, + time + FROM sensors_events + WHERE client_platform IS NOT NULL + LIMIT 20 + """ + + cursor.execute(sql_sample) + samples = cursor.fetchall() + + print(f"{'ID':<15} {'client_platform':<20} {'platform':<15} {'browser':<20} {'browser_language':<15} {'event':<30}") + print("-" * 140) + + for sample in samples: + id_val = str(sample[0]) + client_platform = sample[1] if sample[1] else '' + platform = sample[2] if sample[2] else '' + browser = sample[3] if sample[3] else '' + browser_language = sample[4] if sample[4] else '' + event = sample[6] if sample[6] else '' + + # 截断过长的字段 + event = (event[:27] + '..') if len(event) > 30 else event + + print(f"{id_val:<15} {client_platform:<20} {platform:<15} {browser:<20} {browser_language:<15} {event:<30}") + + print("-" * 140) + print(f"总计: {len(samples)} 条示例记录") + + # 查询 client_platform 和 platform 的组合分布 + print("\n" + "=" * 100) + print("client_platform 与 platform 的组合分布") + print("=" * 100) + + sql_combo = """ + SELECT + client_platform, + platform, + COUNT(*) as count + FROM sensors_events + WHERE client_platform IS NOT NULL + AND platform IS NOT NULL + GROUP BY client_platform, platform + ORDER BY client_platform, count DESC + """ + + cursor.execute(sql_combo) + combos = cursor.fetchall() + + current_platform = None + for combo in combos: + client_platform = combo[0] + platform = combo[1] + count = combo[2] + + if client_platform != current_platform: + print(f"\n【{client_platform}】") + current_platform = client_platform + + print(f" {platform:<30} {count:>12,} 条") + + except Exception as e: + print(f"查询失败: {e}") + import traceback + traceback.print_exc() + finally: + if 'connection' in locals(): + connection.close() + +if __name__ == "__main__": + query_client_platform() diff --git a/offline_tasks/test/query_sensors_fields.py b/offline_tasks/test/query_sensors_fields.py new file mode 100644 index 0000000..be75ab8 --- /dev/null +++ b/offline_tasks/test/query_sensors_fields.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""查询 sensors_events 表的字段信息""" + +import os +import pymysql +import sys +sys.path.append(os.path.dirname(os.path.abspath(__file__))) +from config.offline_config import DB_CONFIG + +def query_table_structure(): + """查询表结构""" + 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: + # 查询表结构 + sql = "DESCRIBE sensors_events" + cursor.execute(sql) + result = cursor.fetchall() + + print("=" * 100) + print(f"{'字段名':<30} {'类型':<25} {'允许NULL':<10} {'键':<10} {'额外信息'}") + print("=" * 100) + + for row in result: + field = row[0] + type_info = row[1] + null = row[2] + key = row[3] + extra = row[5] if len(row) > 5 else '' + + # 只显示主要字段 + if any(keyword in field.lower() for keyword in ['platform', 'browser', 'device', 'event', 'time', 'user', 'id']): + print(f"{field:<30} {type_info:<25} {null:<10} {key:<10} {extra}") + + print("=" * 100) + print(f"\n表总共有 {len(result)} 个字段") + + # 查询 client_platform 的详细分布 + print("\n" + "=" * 80) + print("client_platform 字段值分布详情") + print("=" * 80) + + sql_platform = """ + SELECT + client_platform, + COUNT(*) as count, + ROUND(COUNT(*) * 100.0 / SUM(COUNT(*)) OVER(), 2) as percentage + FROM sensors_events + GROUP BY client_platform + ORDER BY count DESC + """ + + cursor.execute(sql_platform) + platforms = cursor.fetchall() + + print(f"{'client_platform':<20} {'记录数':>15} {'占比':>10}") + print("-" * 80) + + for plat in platforms: + platform = plat[0] if plat[0] else '(NULL)' + count = plat[1] + percentage = plat[2] if plat[2] else 0 + print(f"{platform:<20} {count:>15,} {percentage:>10}%") + + # 查询示例数据 + print("\n" + "=" * 120) + print("示例记录(包含 client_platform 相关字段)") + print("=" * 120) + + # 获取所有字段名 + cursor.execute("DESCRIBE sensors_events") + all_fields = [row[0] for row in cursor.fetchall()] + + # 选择相关字段进行展示 + display_fields = [] + for field in all_fields: + if any(keyword in field.lower() for keyword in ['id', 'platform', 'browser', 'device', 'event', 'time', 'user', 'type']): + display_fields.append(field) + + # 限制显示字段数量 + display_fields = display_fields[:8] + + sql_sample = f""" + SELECT {', '.join(display_fields)} + FROM sensors_events + LIMIT 10 + """ + + cursor.execute(sql_sample) + samples = cursor.fetchall() + + # 打印表头 + header = " | ".join([f"{field:<15}" for field in display_fields]) + print(header) + print("-" * len(header)) + + # 打印数据 + for sample in samples: + row_data = [] + for i, val in enumerate(sample): + if val is None: + row_data.append(f"{'NULL':<15}") + elif isinstance(val, str): + val_str = (val[:12] + '..') if len(val) > 15 else val + row_data.append(f"{val_str:<15}") + else: + row_data.append(f"{str(val):<15}") + print(" | ".join(row_data)) + + except Exception as e: + print(f"查询失败: {e}") + import traceback + traceback.print_exc() + finally: + if 'connection' in locals(): + connection.close() + +if __name__ == "__main__": + query_table_structure() diff --git a/offline_tasks/test/query_sensors_platform_combo.py b/offline_tasks/test/query_sensors_platform_combo.py new file mode 100644 index 0000000..5597d08 --- /dev/null +++ b/offline_tasks/test/query_sensors_platform_combo.py @@ -0,0 +1,146 @@ +#!/usr/bin/env python3 +"""查询 sensors_events 表的 platform 组合分布""" + +import os +import pymysql +import sys +sys.path.append(os.path.dirname(os.path.abspath(__file__))) +from config.offline_config import DB_CONFIG + +def query_platform_combinations(): + """查询 platform 相关字段的组合分布""" + 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: + print("=" * 100) + print("client_platform 与 business_platform 的组合分布") + print("=" * 100) + + sql = """ + SELECT + client_platform, + business_platform, + COUNT(*) as count, + ROUND(COUNT(*) * 100.0 / SUM(COUNT(*)) OVER(PARTITION BY client_platform), 2) as percentage_in_client + FROM sensors_events + WHERE client_platform IS NOT NULL + AND business_platform IS NOT NULL + GROUP BY client_platform, business_platform + ORDER BY client_platform, count DESC + """ + + cursor.execute(sql) + result = cursor.fetchall() + + current_platform = None + for row in result: + client_platform = row[0] + business_platform = row[1] + count = row[2] + percentage = row[3] + + if client_platform != current_platform: + print(f"\n【client_platform = {client_platform}】") + current_platform = client_platform + + print(f" business_platform: {business_platform:<20} | 数量: {count:>12,} | 占该平台: {percentage:>6}%") + + # 查询不同 client_platform 的用户行为统计 + print("\n" + "=" * 100) + print("不同 client_platform 的用户行为统计") + print("=" * 100) + + sql_events = """ + SELECT + client_platform, + event, + COUNT(*) as count + FROM sensors_events + WHERE client_platform IS NOT NULL + AND event IS NOT NULL + GROUP BY client_platform, event + ORDER BY client_platform, count DESC + """ + + cursor.execute(sql_events) + events = cursor.fetchall() + + current_platform = None + event_count = 0 + max_events = 5 # 每个平台最多显示5个事件 + + for row in events: + client_platform = row[0] + event = row[1] + count = row[2] + + if client_platform != current_platform: + if current_platform is not None: + print("") + print(f"\n【client_platform = {client_platform}】Top 事件:") + current_platform = client_platform + event_count = 0 + + if event_count < max_events: + print(f" {event:<40} | {count:>12,}") + event_count += 1 + + # 查询不同 client_platform 的时间分布 + print("\n" + "=" * 100) + print("不同 client_platform 的时间分布(最近30天)") + print("=" * 100) + + sql_time = """ + SELECT + client_platform, + DATE(create_time) as event_date, + COUNT(*) as count + FROM sensors_events + WHERE client_platform IS NOT NULL + AND create_time >= DATE_SUB(CURDATE(), INTERVAL 30 DAY) + GROUP BY client_platform, DATE(create_time) + ORDER BY client_platform, event_date DESC + LIMIT 30 + """ + + cursor.execute(sql_time) + time_data = cursor.fetchall() + + current_platform = None + day_count = 0 + max_days = 5 # 每个平台最多显示5天 + + for row in time_data: + client_platform = row[0] + event_date = str(row[1]) + count = row[2] + + if client_platform != current_platform: + if current_platform is not None: + print("") + print(f"\n【client_platform = {client_platform}】最近活动:") + current_platform = client_platform + day_count = 0 + + if day_count < max_days: + print(f" {event_date} | {count:>12,}") + day_count += 1 + + except Exception as e: + print(f"查询失败: {e}") + import traceback + traceback.print_exc() + finally: + if 'connection' in locals(): + connection.close() + +if __name__ == "__main__": + query_platform_combinations() diff --git a/offline_tasks/test/verify_buyer_nature_source.py b/offline_tasks/test/verify_buyer_nature_source.py new file mode 100644 index 0000000..d8afb00 --- /dev/null +++ b/offline_tasks/test/verify_buyer_nature_source.py @@ -0,0 +1,191 @@ +#!/usr/bin/env python3 +"""验证 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 verify_buyer_nature_source(): + """验证 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: + print("=" * 120) + print(" 验证 buyer_nature 字典信息的来源") + print("=" * 120) + + # 1. 查询 pub_dict_category 表,确认 buyer_nature 类别存在 + print("\n【步骤1】查询 pub_dict_category 表,确认 buyer_nature 字典类别") + print("=" * 120) + + sql = """ + SELECT code, name, id + FROM pub_dict_category + WHERE code = 'buyer_nature' + """ + cursor.execute(sql) + category_result = cursor.fetchall() + + if category_result: + for row in category_result: + print(f"\n✓ 找到字典类别:") + print(f" - ID: {row[2]}") + print(f" - code: {row[0]}") + print(f" - name: {row[1]}") + else: + print("\n✗ 未找到 buyer_nature 字典类别") + return + + # 2. 查询 pub_dict_item 表,获取 buyer_nature 的所有字典项 + print("\n" + "=" * 120) + print("【步骤2】查询 pub_dict_item 表,获取 buyer_nature 的所有字典项") + print("=" * 120) + + sql = """ + SELECT id, code, name, sort_order, is_enable, is_delete + FROM pub_dict_item + WHERE category_code = 'buyer_nature' + ORDER BY sort_order, code + """ + cursor.execute(sql) + items = cursor.fetchall() + + if items: + print(f"\n✓ 找到 {len(items)} 个字典项:\n") + print(f"{'ID':<10} {'code':<10} {'name':<40} {'sort_order':<15} {'is_enable':<10} {'is_delete':<10}") + print("-" * 120) + + for item in items: + item_id = item[0] + code = str(item[1]) if item[1] else 'NULL' + name = item[2] if item[2] else 'NULL' + sort_order = item[3] if item[3] else 'NULL' + is_enable = item[4] if item[4] is not None else 'NULL' + is_delete = item[5] if item[5] is not None else 'NULL' + + print(f"{item_id:<10} {code:<10} {name:<40} {sort_order:<15} {is_enable:<10} {is_delete:<10}") + else: + print("\n✗ 未找到字典项") + + # 3. 查询 pub_dict_item_lang 表,获取多语言翻译 + print("\n" + "=" * 120) + print("【步骤3】查询 pub_dict_item_lang 表,获取多语言翻译") + print("=" * 120) + + sql = """ + SELECT i.id, i.code, i.name as zh_name, + il.lang, il.name as lang_name + FROM pub_dict_item i + LEFT JOIN pub_dict_item_lang il ON i.id = il.dict_item_id + WHERE i.category_code = 'buyer_nature' + ORDER BY i.sort_order, i.code, il.lang + """ + cursor.execute(sql) + lang_items = cursor.fetchall() + + if lang_items: + print(f"\n✓ 找到 {len(lang_items)} 条翻译记录:\n") + print(f"{'ID':<8} {'code':<8} {'中文名称':<25} {'lang':<8} {'翻译名称'}") + print("-" * 120) + + current_code = None + for item in lang_items: + item_id = item[0] + code = str(item[1]) if item[1] else 'NULL' + zh_name = item[2] if item[2] else 'NULL' + lang = item[3] if item[3] else 'NULL' + lang_name = item[4] if item[4] else '' + + if code != current_code: + if current_code is not None: + print() # 空行分隔 + current_code = code + + lang_display = f"{lang}:" if lang else '' + print(f"{item_id:<8} {code:<8} {zh_name:<25} {lang_display:<8} {lang_name}") + else: + print("\n✗ 未找到翻译记录") + + # 4. 总结信息来源 + print("\n" + "=" * 120) + print("【总结】buyer_nature 字典信息的来源") + print("=" * 120) + + print(""" +这些信息来源于数据库中的字典表系统: + +1️⃣ pub_dict_category(字典类别表) + - 存储字典类别定义 + - buyer_nature 是其中一个类别,表示"公司性质" + +2️⃣ pub_dict_item(字典项表) + - 存储具体的字典项 + - 包含字段:id, category_code, code, name, sort_order 等 + - buyer_nature 的字典项包括: + • code=1, name="贸易公司" + • code=2, name="零售商" + • code=3, name="批发商" + • code=4, name="分销商" + • code=5, name="代理商" + • code=6, name="自有品牌" + • code=7, name="其他" + +3️⃣ pub_dict_item_lang(字典项多语言表) + - 存储字典项的多语言翻译 + - 包含字段:dict_item_id, lang, name 等 + - 支持 zh(中文), en(英文), ru(俄语) 等多种语言 + +💡 数据库结构: + pub_dict_category (1) ←→ (N) pub_dict_item (1) ←→ (N) pub_dict_item_lang + ↓ ↓ ↓ + 字典类别定义 具体字典项 多语言翻译 + +⚠️ 重要发现: + - buyer_nature 字典在数据库中已定义 + - 但 buy_buyer 表中并没有使用这个字段 + - 这是一个"已定义但未使用"的字典 + """) + + # 5. 验证表结构 + print("\n" + "=" * 120) + print("【验证】显示相关表结构") + print("=" * 120) + + print("\n1️⃣ pub_dict_category 表结构(关键字段):") + cursor.execute("DESCRIBE pub_dict_category") + cols = cursor.fetchall() + for col in cols[:10]: + print(f" - {col[0]:<20} {col[1]:<20}") + + print("\n2️⃣ pub_dict_item 表结构(关键字段):") + cursor.execute("DESCRIBE pub_dict_item") + cols = cursor.fetchall() + for col in cols[:15]: + print(f" - {col[0]:<30} {col[1]:<20}") + + print("\n3️⃣ pub_dict_item_lang 表结构(关键字段):") + cursor.execute("DESCRIBE pub_dict_item_lang") + cols = cursor.fetchall() + for col in cols[:10]: + print(f" - {col[0]:<30} {col[1]:<20}") + + except Exception as e: + print(f"查询失败: {e}") + import traceback + traceback.print_exc() + finally: + if 'connection' in locals(): + connection.close() + +if __name__ == "__main__": + verify_buyer_nature_source() -- libgit2 0.21.2