Mysql JOIN 子查询

Posted

技术标签:

【中文标题】Mysql JOIN 子查询【英文标题】:Mysql JOIN subquery 【发布时间】:2014-01-14 08:36:52 【问题描述】:

我应该如何查询哪里

我有 (table1) 行,在其他表中可以没有或有几行引用它 这些引用 (table2) 行的 colum1 可以为 null 或 date

我希望 table1 中的所有行在 table2 中所有行 column1 不为空或根本没有行。

当然,基本的 sql 是这样的:

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

但接下来会发生什么?

【问题讨论】:

【参考方案1】:

您可以像SUM(CASE WHEN table2.col IS NULL THEN 1 ELSE 0 END) AS nullcount 这样在查询中计算空值的出现次数,我假设table2.col 是其中日期为空值的那个

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 

【讨论】:

@AngularAddict 见working fiddle where 和 have 是有区别的 好的。谢谢。但是如何获得 id=2 的 c_contact 行,因为它在 c_monitoring 中没有引用。实际上我想要的是来自 c_contact 的行,在 c_cmonitoring 中没有行或所有 c_monitoring 结束的行都是日期,而不是空值。更新小提琴:sqlfiddle.com/#!2/f7b17/4 @AngularAddict 请参阅second query 我在 on 子句中添加了一个条件,并且有 0 个空日期的行第一次查询只是为了显示数据集 @AngularAddict 尝试使用exists fiddle 查询您的查询,但不存在也会使您的查询变慢 @AngularAddict 添加这两个索引如果你还没有添加 ALTER TABLE c_contact ADD INDEX test (securityid);更改表c_monitoring 添加索引test1 (securityid);

以上是关于Mysql JOIN 子查询的主要内容,如果未能解决你的问题,请参考以下文章

JOIN 语法中的 MySQL 相关子查询

MySql子查询(wherefromexists)及连接查询(left joinright joininner joinunion join)

MySQL INNER JOIN 查询中包含子查询的问题

为啥 MySQL JOIN 比 WHERE IN (子查询) 快得多

MySQL - 如何在 JOIN 中使用相关子查询

加入后 MySQL 限制 LEFT JOIN 子查询