简体   繁体   English

如何运行以下查询?

[英]How do I run the following query?

I have to table A and B. The relationship is one to many. 我必须表A和B.这种关系是一对多的。 In table B have foreign key from A. 在表B中有来自A的外键。

TABLE A:
   ... fields

TABLE B:
   f = foreignkey(A)

How to get all A without B ? 如何在没有B的情况下获得所有A?

The query below is not working. 以下查询无效。

select TABLE_A.id, COUNT(TABLE_B.f)  
from TABLE_A JOIN TABLE_B 
   ON (TABLE_A.id = TABLE_B.f) 
GROUP BY TABLE_A.id HAVING COUNT(TABLE_B.f) = 0; 

Change JOIN to LEFT JOIN : 更改JOINLEFT JOIN

TABLE_A.id, COUNT(TABLE_B.f) 
from TABLE_A 
LEFT JOIN TABLE_B ON (TABLE_A.id = TABLE_B.f) 
GROUP BY TABLE_A.id 
HAVING COUNT(TABLE_B.f) = 0;

Use not exists ? 使用not exists

select a.*
from table_a a
where not exists (select 1
                  from table_b b
                  where a.id = b.f
                 );

Or not in . 或者not in Or left join with where . 或者left join where

You can do a LEFT JOIN and take only the rows that have NULL in the column TABLE_B.f , 你可以执行LEFT JOIN并只获取TABLE_B.f列中有NULL的行,
meaning that there is no TABLE_B.f to match TABLE_A.id : 意味着没有TABLE_B.f匹配TABLE_A.id

SELECT TABLE_A.id  
FROM TABLE_A LEFT JOIN TABLE_B 
ON TABLE_A.id = TABLE_B.f 
WHERE TABLE_B.f IS NULL;

assuming that TABLE_A.id is unique in TABLE_A , 假设TABLE_A.idTABLE_A是唯一的,
otherwise use 否则使用

SELECT DISTINCT TABLE_A.id  

You can use the left join and check the nullity on right table. 您可以使用左连接并检查右表上的无效。

SELECT TABLE_A.id,count(*)  
FROM TABLE_A LEFT JOIN TABLE_B 
ON TABLE_A.id = TABLE_B.f 
WHERE TABLE_B.f IS NULL
group by TABLE_A.id;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM