Jump to content

aliase issue


Brian W

Recommended Posts

I aliased the results of a subquery and need to tell the query to use the resulting value in the WHERE clause.

MySQL Error: Unknown column 'Tasks' in 'where clause'

SELECT

p.project, p.id as pid, p.acronym, p.Client as cid, c.client,

(SELECT COUNT(t.Task) FROM tasks t WHERE t.pid = p.id GROUP BY t.pid) as Tasks

FROM projects p

LEFT JOIN clients c ON p.Client = c.id

WHERE

Tasks > 0

ORDER BY project ASC

 

Link to comment
https://forums.phpfreaks.com/topic/167034-aliase-issue/
Share on other sites

Hi

 

Alias the column name as well

 

SELECT

p.project, p.id as pid, p.acronym, p.Client as cid, c.client,

(SELECT COUNT(t.Task) AS Fred FROM tasks t WHERE t.pid = p.id GROUP BY t.pid) as Tasks

FROM projects p

LEFT JOIN clients c ON p.Client = c.id

WHERE

Tasks.Fred > 0

ORDER BY project ASC

 

All the best

 

Keith

 

Link to comment
https://forums.phpfreaks.com/topic/167034-aliase-issue/#findComment-880692
Share on other sites

kickstart, that idea didn't work. It seems to me that whatever is inside the sub-query can't be used in the sup-query's WHERE clause.

 

I have given the user the option to hide "projects" in which no tasks are open.

 

How can I use HAVING? I need to not return the project if there are no tasks.

 

Before I began using the subquery, I was using a LEFT JOIN with the project table on the left but it would not return projects that had no tasks, it needs to be an optional filter.

 

Thanks guys

Link to comment
https://forums.phpfreaks.com/topic/167034-aliase-issue/#findComment-880752
Share on other sites

Hi

 

Sorry, I misread the issue.

 

Maq is correct that you can use a HAVING clause (like a WHERE, but done later), or you could use an extra outer join. Something like (probably some typos):-

 

SELECT

p.project, p.id as pid, p.acronym, p.Client as cid, c.client,

(SELECT COUNT(t.Task) AS Fred FROM tasks t WHERE t.pid = p.id GROUP BY t.pid) as Tasks

FROM projects p

LEFT OUTER JOIN clients c ON p.Client = c.id

LEFT OUTER JOIN (SELECT pid, COUNT(Task) AS Fred FROM tasks t GROUP BY pid) t ON p.id =t.pid

WHERE t.Fred > 0

ORDER BY project ASC

 

All the best

 

Keith

Link to comment
https://forums.phpfreaks.com/topic/167034-aliase-issue/#findComment-880765
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.