简体   繁体   English

Mysql JOIN子查询

[英]Mysql JOIN subquery

How should I do query where 我应该如何查询

  • I have (table1) row which can have none or several rows referencing to it in other table 我有(table1)行,在其他表中可以没有任何行或几行引用它
  • These referencing (table2) rows have colum1 that can be null or date 这些引用(表2)行的colum1可以为null或日期

I would like to have all rows from table1 which have all rows column1 not as null or no rows at all, in table2. 我想让table1中的所有行都具有table2中的所有列column1不为null或根本没有任何行。

Of course the basic sql goes like: 当然,基本的sql是这样的:

SELECT table1.* FROM table1 JOIN table2 ON table2.id = table1.table2_id

But what comes next? 但是接下来呢?

You can count the occurences of null in your query like SUM(CASE WHEN table2.col IS NULL THEN 1 ELSE 0 END) AS nullcount , i assume table2.col is the one which has date of null in it 您可以像SUM(CASE WHEN table2.col IS NULL THEN 1 ELSE 0 END) AS nullcount这样的查询来计算查询中null的出现, SUM(CASE WHEN table2.col IS NULL THEN 1 ELSE 0 END) AS nullcount ,我假设table2.col是其中日期为null的那个

SELECT 
  table1.*,
  SUM(
    CASE
      WHEN table2.col IS NULL 
      THEN 1 
      ELSE 0 
    END
  ) AS nullcount 
FROM
  table1 
  JOIN table2 
    ON table2.id = table1.table2_id 
HAVING nullcount > 0 

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

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