使用 oracle 关联 student 和 test表,student的id等于test的student_id。test表里面有一个isdelete字段,查询test表的isdelete字段的值1出现多少次,2出现多少次
时间: 2024-02-21 07:59:54 浏览: 70
可以使用以下SQL语句查询test表isdelete字段值为1和2的出现次数:
```
SELECT
SUM(CASE WHEN isdelete = 1 THEN 1 ELSE 0 END) AS count_1,
SUM(CASE WHEN isdelete = 2 THEN 1 ELSE 0 END) AS count_2
FROM
student s
JOIN test t ON s.id = t.student_id
```
其中,使用了SUM和CASE WHEN语句对isdelete字段进行条件判断,并将符合条件的行计数。通过联接student表和test表,确保只计数与学生相关的测试。
相关问题
使用 oracle 关联 student 和 test表,test表里面有一个isdelete字段,查询test表的isdelete字段的值1出现多少次,2出现多少次
可以使用以下SQL语句查询test表isdelete字段值为1和2的出现次数:
```
SELECT
SUM(CASE WHEN isdelete = 1 THEN 1 ELSE 0 END) AS count_1,
SUM(CASE WHEN isdelete = 2 THEN 1 ELSE 0 END) AS count_2
FROM
student s
JOIN test t ON s.student_id = t.student_id
```
其中,使用了SUM和CASE WHEN语句对isdelete字段进行条件判断,并将符合条件的行计数。最后,通过联接student表和test表,确保只计数与学生相关的测试。
优化以下python中三个mysql查询语句,得到三个独立的结果 sql = '''select id,name_work,date_z,isDelete,biaozhun from dubanworks where id_person='{0}' order by isDelete desc,id desc '''.format(id_person) co.to_sql(sql) jg1 = cs.fetchall() sql = '''select id,name_work,date_z,isDelete,biaozhun from dubanworks where id_fenguan like '#{0}#' order by isDelete desc,id desc '''.format(id_person) co.to_sql(sql) jg2 = cs.fetchall() sql = '''select id,name_work,date_z,isDelete,biaozhun from dubanworks where id_weijieshuo='#{0}#' order by isDelete desc,id desc '''.format(id_person) x = co.to_sql(sql) co.to_sql(sql) jg3 = cs.fetchall() data ={"A":jg1,"B",jg2,"C",jg3}
优化后的代码如下:
```
sql1 = '''SELECT id, name_work, date_z, isDelete, biaozhun FROM dubanworks WHERE id_person=%s ORDER BY isDelete DESC, id DESC'''
cs.execute(sql1, (id_person,))
jg1 = cs.fetchall()
sql2 = '''SELECT id, name_work, date_z, isDelete, biaozhun FROM dubanworks WHERE id_fenguan LIKE %s ORDER BY isDelete DESC, id DESC'''
cs.execute(sql2, ('#' + id_person + '#',))
jg2 = cs.fetchall()
sql3 = '''SELECT id, name_work, date_z, isDelete, biaozhun FROM dubanworks WHERE id_weijieshuo=%s ORDER BY isDelete DESC, id DESC'''
cs.execute(sql3, ('#' + id_person + '#',))
jg3 = cs.fetchall()
data = {"A": jg1, "B": jg2, "C": jg3}
```
这里使用了参数化查询,避免了SQL注入的风险。同时,将SQL语句拆分为三个独立的查询,使用不同的参数,避免了使用WHERE子句中的OR操作符。此外,使用了更加清晰的命名,使得代码更易读。
阅读全文