所以我想使用cursor.execute在Django中运行查询:
def get_user_history(user_id):
with connection.cursor() as cursor:
cursor.execute("""
SET @user_id = %s;
SELECT * FROM (
SELECT channel_id, NULL as article_id, NULL as comment_id,
NULL as friend_id, NULL as followed_channel_id,
NULL as liked_article_id, created_at
FROM channel WHERE user_id = @user_id
UNION ALL
SELECT channel_id, article_id, NULL as comment_id,
NULL as friend_id, NULL as followed_channel_id,
NULL as liked_article_id, created_at
FROM article WHERE channel_id in
(SELECT channel_id from channel where user_id = @user_id)
UNION ALL
SELECT NULL as channel_id, article_id, comment_id,
NULL as friend_id, NULL as followed_channel_id,
NULL as liked_article_id, created_at
FROM comment WHERE user_id = @user_id
UNION ALL
SELECT NULL as channel_id, NULL as article_id, NULL as comment_id,
friend_id, NULL as followed_channel_id,
NULL as liked_article_id, created_at
FROM user_friends WHERE user_id = @user_id
UNION ALL
SELECT NULL as channel_id, NULL as article_id, NULL as comment_id,
NULL as friend_id, channel_id as followed_channel_id,
NULL as liked_article_id, created_at
FROM user_follows_channel WHERE user_id = @user_id
UNION ALL
SELECT NULL as channel_id, NULL as article_id, NULL as comment_id,
NULL as friend_id, NULL as followed_channel_id,
article_id as liked_article_id, created_at
FROM user_likes_article WHERE user_id = @user_id
) T1
ORDER BY created_at;
""", [user_id])
if cursor.fetchall():
return dictfetchall(cursor)
else:
return {'error': 'history is empty'}
但它返回一个空对象[],但是当我在mariaDB中使用
运行完全相同的sql代码时mysql -u root -p
它会返回我想要的正确结果:
+------------+------------+------------+-----------+---------------------+------------------+---------------------+
| channel_id | article_id | comment_id | friend_id | followed_channel_id | liked_article_id | created_at |
+------------+------------+------------+-----------+---------------------+------------------+---------------------+
| 3 | NULL | NULL | NULL | NULL | NULL | 2017-12-04 01:44:35 |
| 3 | 5 | NULL | NULL | NULL | NULL | 2017-12-04 15:40:23 |
| 3 | 6 | NULL | NULL | NULL | NULL | 2017-12-04 16:34:57 |
+------------+------------+------------+-----------+---------------------+------------------+---------------------+
我完全难过了。