简体   繁体   中英

How to write mysql query for this?

I want query which output all job_ID whose labor has been done(JobDone) 在此处输入图片说明

I've tried to use inner join on the query but have failed to accomplish what I seek.

SELECT * FROM `jobs` WHERE Status='JobDone' GROUP BY Job_id

Above query also return the value whose only one job is done.

使用join query获取结果

select j1.Name,j2.Labor from jobcard j1 innerjoin jobs j2 on j1.job_ID=j2.job_ID where j2.Status='JobDone' GROUP BY j2.job_ID

I think this is the query you have in mind:

SELECT j1.*, c.*
FROM jobs j1
INNER JOIN
(
    SELECT Job_ID
    FROM jobs
    GROUP BY Job_ID
    HAVING SUM(CASE WHEN Status <> 'JobDone' THEN 1 ELSE 0 END) = 0
) j2
    ON j1.Job_ID = j2.Job_ID
INNER JOIN Jobcard c
    ON t1.Job_ID = c.Job_ID

The subquery aggregates over Job_id and asserts that every status is completed. This subquery produces a set of IDs which is then used to determine which full records to select from your table.

I also included a join to the Jobcard table though you are free to remove it if you want.

尝试这个

SELECT Job_ID FROM Jobs WHERE Status LIKE 'JobDone'
SELECT  a.Job_id,a.Labor,c.Name
FROM `jobs` a
   left join Jobcard c on a.Job_id=c.Job_id    
WHERE not exists (select b.Job_id
                  FROM jobs b
                  WHERE Status<>'JobDone' AND b.Job_id=a.Job_id) 

If you want the name from Jobcard table also, use below query:

SELECT * FROM JOBCARD JC
JOIN JOBS J ON JC.job_ID = J.job_ID
WHERE J.Status = 'jobDone'

And if you don't want to get name, no need to join tables, use below query:

select * from jobs where Status='jobDone'

You should get through : Join with sql

anyway here's your answer..

select job_ID from JobCard Inner join Jobs On JobCard.job_ID = Job.job_ID where status = 'jobDone' group by Job.labor .

Simple as:

Select jobcard.job_id, jobs.labor from jobcard 
inner join jobs on jobs.job_id = jobcard.job_id 
where jobs.status = 'JobDone';

Note that what you've wrote:

SELECT * FROM `jobs` WHERE Status='JobDone' GROUP BY Job_id 

does not show the full list of jobs that is done, because you are grouping by job_id. The correct to your statement would be :

SELECT * FROM `jobs` WHERE Status='JobDone'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM