1

a bit of background...

I currently have a client area for clients to login and see their job's progress and leave any comments etc. In the client area, I have an admin area where it enables me to login and view all of the jobs. Everything is working fine, but i'd like to be able to sort it a bit neater.

The database consists of 4 tables, 2 of these are relevant to this query... Jobs and Posts. Currently the list just shows a full list of jobs for every client using the following:

$result = mysql_query("SELECT * FROM Jobs ORDER BY date DESC"); 

Then:

<a href="jobdetail.php?clientid='. $row['ClientID'].'&jobid='.$row['JobNumber'].'">'. $row['Username'].' - '. $row['ClientID'].'.'.$row['JobNumber'].' - '.$row['Description'].' - '.$row['Status'].'</a>

As you can see, the details are taken from the database and echoed, and the whole thing is then linked to the page that loads the job from their ClientID and JobNumber. All client's can have a job number 1 eg ClientID: 12345 and ClientID: 12346 can both have JobNumber1. At the moment this all works fine, but i'd like to have the the Job that has the newest post related to it in the Posts table at the top, and then the next newest, and so on.

At the moment after some research i've got to this:

SELECT
Jobs.*
FROM Jobs
LEFT JOIN Posts ON Posts.JobNumber=Jobs.JobNumber
GROUP BY
Jobs.ClientID, Jobs.JobNumber
ORDER BY Posts.PostDate

And whilst I am getting all of the results, I am not getting them in order of the date of the post. I have a feeling it is because i'm not actually pulling the PostDate value from the Posts table, but i've tried loads and i'm not managing to get anything to work!

If anyone could give me any pointers it'd be much appreciated. Thank you in advance.

4

2 回答 2

1

得到它的工作:

SELECT
c.ClientID
, j.JobNumber , j.Username , j.Description , j.ClientID , j.Status , j.AdminUnread
, MAX(p.PostDate) as postedOn
FROM Clients c
INNER JOIN Jobs j ON c.ClientID=j.ClientID
LEFT JOIN Posts p ON j.JobNumber=p.JobNumber AND c.ClientID=p.ClientID
GROUP BY
c.ClientID
, j.JobNumber
ORDER BY
postedOn DESC, c.ClientID, j.JobNumber DESC
于 2013-01-24T03:44:16.750 回答
0

尝试这个:

SELECT *  
FROM Jobs j 
INNER JOIN ( SELECT p.* 
             FROM posts p 
             INNER JOIN (SELECT JobNumber, MAX(postdate) postdate 
                         FROM posts GROUP BY jobnumber
                        ) a ON p.JobNumber = a.JobNumber AND a.postdate = p.postdate
           ) p ON p.JobNumber = j.JobNumber 
GROUP BY j.ClientID, j.JobNumber 
ORDER BY p.PostDate;
于 2013-01-19T03:30:39.117 回答