【问题标题】:LEFT JOIN and IS NULL in nested CONCAT returning NULL only嵌套 CONCAT 中的 LEFT JOIN 和 IS NULL 仅返回 NULL
【发布时间】:2023-03-26 03:39:01
【问题描述】:

每个学生有多个支付时间段,我想获取未支付费用的时间段,或者MySQL语言 - 获取不在另一个表中的行。

在这里,我在MySQL 中使用嵌套的GROUP_CONCAT,并在LEFT JOIN 中使用IS NULL

表格student - 学生名单

id  |   ttl     |   cls |   sec
===============================
1   |   Rohit   |   1   |   1
2   |   Karuna  |   2   |   0

cls - 类列表

id  |   ttl
===========
1   |   One
2   |   Two

表格sec - 部分列表

id  |   ttl
===========
1   |   A
2   |   B

表格fee_tm - 费用时间段列表

id  |   ttl
===========
1   |   Jan
2   |   Feb

表格std_fee - 分配给学生的费用期限列表

id  |   s_id|   f_id|   fee|    f_tm    
====================================
1   |   1   |   4   |   100|    1

根据表结构和表中的行,我期望使用我的 MySQL 代码跟随输出。

//(student.id-student.cls-student.sec-student rest of the fee.time(Month1,Month2..))

1-Rohit-One-A-Feb,
2-Karuna-Two-John,Feb

但是我得到的(我想申请 NULLLEFT JOIN 仅限收费时间,所以可以获取剩余的收费时间,但这里适用到整个结果)

2-Karuna-Two-

SQL Fiddle

MySQL 代码

  SELECT
    GROUP_CONCAT(DISTINCT CONCAT(student.id,'-',student.ttl,'-',cls.ttl,'-',
          COALESCE(sec.ttl,''),
          COALESCE(CONCAT('-',fee_tm.ttl),'')) 
    ORDER BY student.id) AS stdt
  FROM
    student
  JOIN
    cls ON cls.id=student.cls
  LEFT JOIN
    sec ON sec.id=student.sec
  LEFT JOIN
    std_fee ON std_fee.s_id = student.id
  LEFT JOIN
    fee_tm ON fee_tm.id = std_fee.f_tm
  WHERE
    std_fee.f_tm IS NUll

【问题讨论】:

  • 尝试将WHERE std_fee.f_tm IS NULL 移至ON 子句。

标签: mysql sql group-by left-join group-concat


【解决方案1】:

您可以尝试为std_feefee_tm 表编写子查询,并在ON 中设置std_fee.f_tm IS NUll 条件以生成结果集。

输入whereON之间的条件有什么区别?

您正在使用OUTER JOIN,如果您不在ON 中添加条件,您将错过此std_fee.f_tm IS NUll 条件下的行数据,因为您在fee_tm.id = std_fee.f_tm 中匹配

查询看起来像这样。

查询 1

SELECT
    GROUP_CONCAT(DISTINCT CONCAT(student.id,'-',student.ttl,'-',cls.ttl,'-',
          COALESCE(sec.ttl,''),
          COALESCE(CONCAT(t1.ttl),'')) 
    ORDER BY student.id) AS stdt
  FROM
    student
  JOIN
    cls ON cls.id=student.cls
  LEFT JOIN
    sec ON sec.id=student.sec
   LEFT JOIN
   (
      select s.id,GROUP_CONCAT(COALESCE(fee_tm.ttl,'')) ttl
      FROM
          student s
      LEFT JOIN
          std_fee ON std_fee.s_id = s.id
      LEFT JOIN
          fee_tm ON fee_tm.id = std_fee.f_tm  or std_fee.f_tm IS NUll
      GROUP BY s.id
   ) t1 on t1.id = student.id
   group by student.id

Results

|                 stdt |
|----------------------|
| 1-Rohit-One-AJan     |
| 2-Karuna-Two-Jan,Feb |

【讨论】:

  • 谢谢,但我认为您不理解我的预期输出。在ON 子句中添加std_fee.f_tm IS NUll,我得到以下结果-1-Rohit-One-A,2-Karuna-Two-,这里缺少所有费用月份,我需要1-Rohit-One-A-Feb,2-Karuna-Two-Jan, Feb。因此,我尝试在您的答案中替换 OR 而不是 AND。我接近我的期望。 1-Rohit-One-Jan,2-Karuna-Two-Feb,2-Karuna-Two-Jan 但仍然无法得到准确的结果。 link
  • @Dipak 你需要使用group by 子句作为学生ID
  • @Dipak 没问题很高兴为您提供帮助 :)
猜你喜欢
  • 1970-01-01
  • 2019-03-25
  • 1970-01-01
  • 2016-05-07
  • 1970-01-01
  • 1970-01-01
  • 2015-09-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多