MariaDB 中的 SQL 如何将 2 列中的数据用于另一列中的 select 值?

SQL in MariaDB How to use data from 2 columns to select values from another column?

具体问题是来自 class table 的 select rollno 谁出现在 dbms 中而不出现在数学中。

rollno sts sub
1      1    dbms
1      0    maths
2      1    dbms
2      0    maths
3      0    dbms
3      1    maths
4      0    dbms
4      0    maths
5      1    dbms
5      1    maths

您可以为此使用条件聚合:

select rollno
from mytable
group by rollno
having sum(sub = 'dbms' and sts = 1) > 0
   and sum(sub = 'maths' and sts = 1) = 0

这利用了 MySQL 中 true 的计算结果为 1 而 false 的计算结果为 0 的事实。

  • sum(sub = 'dbms' and sts = 1) 查找 sub 是给定 rollno 的 dbms 的行数,它必须至少为 1
  • sum(sub = 'maths' and sts = 1) 查找 sub 是给定 rollno 的数学的行数,它必须为 0。

Demo

您可以使用两个带 id 而不是

的子选择
select roolno
from my_table 
where sub in (select roolno from my_table  where sub ='dbms')
and sub not in (select roolno from my_table  where sub ='maths' )