每个学生都有多个支付费用的时间段,我想提取尚未支付费用的费用时间段,或者在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
但我得到的是(我只想将 SQL Fiddle MySQL代码NULL
和LEFT JOIN
应用于费用时间,所以剩余的收费时间2-Karuna-Two-
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_fee
和fee_tm
表编写一个子查询,并让std_fee.f_tm IS NUll
在ON
中设置条件以生成结果集。
放入
where
和ON
的条件有什么区别?
您使用的是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 |