如何在MySQL中用变量的定义值替换变量?

时间:2015-06-17 20:48:21

标签: mysql sql

将字符串分配给已定义的变量isWeekdays

set @isWeekdays='calendar.monday=1 AND calendar.tuesday=1 AND calendar.wednesday=1 AND calendar.thursday=1 AND calendar.friday=1';

我希望在执行查询时可以用字符串替换变量isWeekdays,例如,

SELECT * FROM calendar WHERE @isWeekdays;

-- expect to    
SELECT * FROM calendar WHERE calendar.monday=1 AND calendar.tuesday=1 AND calendar.wednesday=1 AND calendar.thursday=1 AND calendar.friday=1;

然而,它没有生效。

2 个答案:

答案 0 :(得分:2)

@isWeekdays将在查询中评估为数字,您必须使用语句,它将作为动态查询:

-- setting the @isWeekdays variable
set @isWeekdays='calendar.monday=1 AND calendar.tuesday=1 
     AND calendar.wednesday=1 AND calendar.thursday=1 
      AND calendar.friday=1';


-- using the @isWeekdays variable in dynamic query
set @sql = concat('SELECT * FROM calendar WHERE ',@isWeekdays);
prepare stmt1 FROM @sql; 
execute stmt1; 
-- you muyst close the prepared statement
deallocate prepare stmt1; 

您可以在同一会话中更改@isWeekdays并再次打开该语句。

那就是它。

答案 1 :(得分:0)

@Notorious Pet0 的帮助下,与动态查询相比,使用脚本语言似乎更好。关键源代码(使用python中的格式字符串)如下所示。

#!/usr/bin/env python
import MySQLdb
import codecs  #for charset utf-8

## connect to MySQL
db = MySQLdb.connect(host="localhost",
        user="root",
        passwd="Jelline", # password
        db="gtfs")  #name of the data base

## create a Cursor object to execute sql queries
cur = db.cursor()

## execute queries
isWeekdays = 'calendar.monday=1 AND calendar.tuesday=1 AND calendar.wednesday=1 AND calendar.thursday=1 AND calendar.friday=1'
sql = 'SELECT * FROM calendar WHERE {isWeekdays}'.format(isWeekdays=isWeekdays)

cur.execute(sql)

## write to a file
with open('test.txt', 'w') as fp : #fp is a file object
    for row in cur.fetchall() :
        s = '\t'.join(str(item) for item in row)
        fp.write(s + '\n')

## clean up
fp.close()
cur.close()
db.close()