我有2张桌子
工作
id | job_num | comp_date
-----------------------------
1 | J01 | NULL
2 | J02 | NULL
3 | J03 | NULL
4 | J04 | NULL
5 | J05 | NULL
易于
id | job_id | status | apt_date | user_id
-----------------------------------------
1 | 1 | 1 | 2018-08-09 | 1
2 | 1 | 1 | 2018-08-09 | 2
3 | 2 | 2 | 2018-08-09 | 1
我正试图从左边的两个表中获取数据,其中限制
SELECT j.* , a.* FROM `job` j
LEFT JOIN apt a
ON j.id = a.job_id AND a.status = 1
Group by a.date
id | job_num | comp_date| id | job_id | status | apt_date
---------------------------------------------------------
2 | J02 | NULL |NULL|NULL | NULL | NULL
1 | J01 | NULL | 1 |1 | 1 | 2018-06-05
我需要来自Job表的所有数据和来自apt table的1个记录状态1
的记录id | job_num | comp_date| id | job_id | status | apt_date
---------------------------------------------------------
1 | J01 | NULL | 1 |1 | 1 | 2018-06-05
2 | J02 | NULL |NULL|NULL | NULL | NULL
3 | J03 | NULL |NULL|NULL | NULL | NULL
4 | J04 | NULL |NULL|NULL | NULL | NULL
5 | J05 | NULL |NULL|NULL | NULL | NULL
如何按记录分组?
答案 0 :(得分:-2)
最后我发现了它。
SELECT j.* , a.* FROM `job` j
LEFT JOIN (SELECT * FROM `apt` WHERE `date` IS NOT NULL AND status =1 GROUP by `date`) as a
ON j.id = a.job_id