简体   繁体   中英

MYSQL correlated subselect in query

I've been trying to get this to work for the last couple of days... I know what I NEED to do, and I have an idea that I need to use a correlated subquery to achieve it, but I've never used a correlated subquery before, and just end up being told that the subselect returns multiple rows... Please can somebody more intelligent than me tell me what I'm doing wrong?

I have three separate tables:

hh_content_creator_jobs - Holds jobs assigned to content creators (using their user id) on our club's website, as well as the id of the last person who edited the item (which may be differen!)

hh_content - Holds content items which the content creators can edit

hh_user_new - Holds a list of usernames and user ranks

So, I have been bashing my head against the following query:

SELECT ccj.content_id, c.title AS page_title, un.username, ccj.assigned_date, ccj.job_status, ccj.last_edit, (SELECT un.username FROM hh_user_new, hh_content_creator_jobs WHERE un.id = ccj.last_edit_by) AS last_edit_by
FROM hh_content_creator_jobs ccj, hh_content c, hh_user_new un
WHERE ccj.content_id = c.id
AND un.id = ccj.assigned_to
ORDER BY ccj.assigned_to

What it SHOULD do is select the content ID, The title of the piece of content, the Username of the person the job's assigned to, the date it was assigned, whether or not it's completed, when it was last edited and (the bit that doesn't work!) the username of the person who last edited it.

It's this final subquery that's giving me problems; What it SHOULD do is take un.id from the main query and use un.id to find un.username in the hh_users_new table... What it SEEMS to be doing is looking up ALL the un.id listings which match... I just want the one that matches the userid stored in hh_content_creator_jobs...

I also considered using a LEFT JOIN, but couldn't get it to work on the basis we sometimes need two sparate values from hh_user_new - the name of the person the job's assigned to and the name of the last person to edit the item...

Can anybody help steer me in the right direction?

Thanks!

Seb

Give this a try:

SELECT ccj.content_id, c.title AS page_title, un.username, ccj.assigned_date, ccj.job_status, ccj.last_edit, (SELECT editor.username FROM hh_user_new editor WHERE editor.id = ccj.last_edit_by) AS last_edit_by
FROM hh_content_creator_jobs ccj, hh_content c, hh_user_new un
WHERE ccj.content_id = c.id
AND un.id = ccj.assigned_to
ORDER BY ccj.assigned_to

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