Return null on condition in sub-table
Say i have 2 tables, person and job.
+--------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------+--------------+------+-----+---------+----------------+
| id | 开发者_运维技巧int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(255) | NO | | NULL | |
| job_id | int(11) | NO | | NULL | |
+--------+--------------+------+-----+---------+----------------+
+----------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------+--------------+------+-----+---------+----------------+
| j_id | int(11) | NO | PRI | NULL | auto_increment |
| j_name | varchar(255) | NO | | NULL | |
| j_active | tinyint(1) | NO | | 0 | |
+----------+--------------+------+-----+---------+----------------+
How would i do a select where it only returns a job_id
where j_active = 1
and otherwise return 0 or NULL? So, I would want to always return all persons but when their job isn't active i dont want to return their job id
select * from person p left join job j on p.job_id=j.j_id and j.j_active=1
A case statement should work. Something like:
select name, case when j_active=1 then job_id else null end as job_id
from person join job on (person.job_id=job.j_id)
精彩评论