嵌套CONCAT中的LEFT JOIN和IS NULL仅返回NULL



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

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

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

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

放入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

结果

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

相关内容

最新更新