仅执行一个查询以从同一表中获取数据

时间:2018-08-01 15:51:26

标签: mysql

在这种情况下,仅对数据库进行一次调用的最佳方法是:

query="""SELECT measure FROM data 
         WHERE id =%s AND pId = %s AND data_type ='total' 
         ORDER BY createdAt DESC LIMIT 1;"""
lines = self.cursor.execute(query,(id,pId))

query="""SELECT measure FROM data 
         WHERE id =%s AND pId = %s AND data_type ='tot_m' 
         ORDER BY createdAt DESC LIMIT 1;"""
lines = self.cursor.execute(query,(id,pId))

工作正常,但是对表进行了2次查询。什么是做一次查询的最佳方法?提前谢谢,对不起我的英语...

1 个答案:

答案 0 :(得分:0)

尝试一下:

query="""SELECT measure FROM data 
         WHERE id =%s AND pId = %s AND data_type ='total' 
         ORDER BY createdAt DESC LIMIT 1;
         UNION
         SELECT measure FROM data 
         WHERE id =%s AND pId = %s AND data_type ='tot_m' 
         ORDER BY createdAt DESC LIMIT 1;"""
lines = self.cursor.execute(query,(id,pId))