两个表
表1
ID FileName
1 abc
2 abc
3 abc
4 xyz
表2
ID Table1_ID isDeleted
1 1 1
2 2 1
3 3 0
4 4 0
我需要通过传递table1的任何ID来获取isDeleted=1的文件名计数,即对于ID的所有值(1,2,3),我需要计数为2
我尝试使用以下查询
SELECT COUNT(t1.FileName) FROM Table1 t1
LEFT OUTER JOIN Table1 t11 ON t1.FileName=t11.FileName
INNER JOIN table2 t2 ON t2.Table1_ID =t1.ID AND t2.isDeleted=1
WHERE t1.ID=X;
X-1,2,3
这总是返回 3。
编辑:我需要通过传递第一个表中的 ID 来获取第一个表中的文件名计数。计数应基于第二个表中的 isdeleted 列。这些表通过列 ID (table1) 和 Table1_ID (table2) 关联
最佳答案
试一下:
select SUM(isDeleted)
from Table2
where Table1_ID in (
select ID from Table1
where FileName = (select FileName
from Table1
where ID = 1)
)
编辑:获取文件计数:
select count(*)
from Table1 a
join Table2 b on a.ID = b.Table1_ID and b.isDeleted = 1
where a.FileName = (select FileName
from Table1
where ID = 1)
关于sql - 在 MySQL 中选择查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4023618/