如何提取SQL查询中提到的所有列沿着Python中所有条件中提到的值。假设我们有以下查询。
SELECT CASE
WHEN grade=90 THEN "A1"
WHEN grade=80 THEN "B1"
WHEN grade=70 THEN "C1"
ELSE "D1"
END as GradeRank, *
FROM employees
WHERE age > 30
AND department = 'sales'
AND salary IN (SELECT salary FROM employees WHERE name like "Adam%")
我想要类似于(列表元素的顺序无关紧要):
output: [("age",30), ("department":"sales"), ("name","Adam%"),("grade",90),("grade",80),("grade",70)]
注意:这只是一个示例查询,可能不是很有效,只是一个随机查询,以测试Python代码,看看我是否能够获得如上所述的输出。
请帮帮我
这是我已经尝试过的。
import re
def extract_conditions(sql_query):
# Regular expression to match SQL conditions
condition_regex = r"\bWHERE\b\s+(.+)\s*(\bGROUP BY\b|\bHAVING\b|\bORDER BY\b|\bSELECT\b|\bLIMIT\b|\bOFFSET\b|\bFETCH\b|\bFOR\b|$)"
# Extract conditions from the SQL query
match = re.search(condition_regex, sql_query, re.IGNORECASE)
if match:
conditions = match.group(1)
# Split conditions by AND or OR operators
conditions = re.split(r"\s+(AND|OR)\s+", conditions, flags=re.IGNORECASE)
# Remove any leading or trailing white space from the conditions
conditions = [c.strip() for c in conditions]
return conditions
else:
return None
# Example SQL query string
sql_query = "SELECT * FROM employees WHERE age > 30 AND department = 'sales' AND salary in (SELECT salary from employees WHERE name like 'Adam%')"
# Extract conditions from the SQL query
conditions = extract_conditions(sql_query)
print(conditions)
预期输出:
output: [("age",30), ("department":"sales"), ("name","Adam%"),("grade",90),("grade",80),("grade",70)]
实际输出:
['age > 30', 'AND', "department = 'sales'", 'AND', "salary in (SELECT salary from employees WHERE name like 'Adam%')"]
1条答案
按热度按时间ckx4rj1h1#
这里有一些可以改进的地方。我可能在这里走了一段很长的路,但你可以对它进行微调。
它适用于单行和多行查询。
验证码:
输出: