python - 如果我使用 mysql 用户变量,python 中的 mysql 不会返回结果
问题描述
我有一个有点复杂的 mysql 查询。我在 DBEAVER 和 mysql 工作台中测试了查询,并得到了正确的结果。但是当我在 python 中执行查询时,我没有得到任何结果。我用 mysql 和 pymysql 试过了。我在单行或多行中尝试过。但仍然只是空的结果。
这是我的代码:
def read_all_locationpairs(version):
sqlstring=f"""
SELECT DISTINCT
from_location_id, to_location_id
FROM
(SELECT
@last_trip_id AS from_trip_id,
@last_trip_id:=trip_id AS to_trip_id,
@last_location_id AS from_location_id,
@last_location_id:=CONCAT_WS(',',location_id,stop) AS to_location_id,
trip_id
FROM
bconn.timetable
WHERE
version_id = {version}
ORDER BY trip_id , start , order_nr) AS trips
WHERE
from_trip_id = to_trip_id
ORDER BY from_location_id , to_location_id limit 5;
""".replace("\n","")
# Same request in a single line with fix version_id
#sqlstring="SELECT DISTINCT from_location_id, to_location_id FROM (SELECT @last_trip_id AS from_trip_id, @last_trip_id:=trip_id AS to_trip_id, @last_location_id AS from_location_id, @last_location_id:=CONCAT_WS(',',location_id,stop) AS to_location_id, trip_id FROM bconn.timetable WHERE version_id = 38 ORDER BY trip_id , start , order_nr) AS trips WHERE from_trip_id = to_trip_id ORDER BY from_location_id , to_location_id"
mycursor = bconndb.cursor()
mycursor.execute(sqlstring)
all_locations=mycursor.fetchall()
print(all_locations)
mycursor.close()
解决方案
我在额外的执行中初始化了变量,而不是我工作正常。
cursor = connection.cursor()
cursor.execute("SET @last_trip_id := null;")
cursor.execute("SET @last_location_id := null;")
cursor.execute(f"""
SELECT DISTINCT
from_location_id, to_location_id
FROM
(SELECT
@last_trip_id AS from_trip_id,
@last_trip_id:=trip_id AS to_trip_id,
@last_location_id AS from_location_id,
@last_location_id:=CONCAT_WS(',',location_id,stop) AS to_location_id,
trip_id
FROM
bconn.timetable
WHERE
version_id = 38
ORDER BY trip_id , start , order_nr) AS trips
WHERE
from_trip_id = to_trip_id
ORDER BY from_location_id , to_location_id
""")
all_locations=cursor.fetchall()
print(all_locations)
cursor.close()
推荐阅读
- matlab - 如何在MATLAB中删除包含某些行中零的矩阵中的所有列
- appium - 由于 xcodebuild 失败,无法在真实设备中启动 appium:“xcodebuild failed with code 65”
- ios - 无法在 Xcode 10.2 中使用 Cocoapods 解组超类
- linux - Yocto 食谱未将文件安装到图像
- php-carbon - 如何在 Carbon 的一周的第一天获得相同的时间?
- android - 为未确定的布局大小添加相对布局背景可绘制 - 中心裁剪
- c++ - '_Wherenode was nullptr' 添加到静态 std::map 时
- java - 检查和更新表中的记录时潜在的并发问题
- python-3.x - 预处理数据时 imputer.fit 出错
- python - Python记录如何在日志中跟踪主机名?