简体   繁体   中英

Left Outer Join query results in an error

This query throws ERROR - [position 0, near 'WHERE' in 'Select path.ePath, path._'] COMMA expected but not found in GROUP BY.

This is my query:

Select path.ePath, path._rowid, doc.Filenumber, COUNT(doc.ePathUID) AS children
from docPath path LEFT OUTER JOIN
     docMeta doc
     ON doc.ePathUID = path._rowid
GROUP BY path._rowid

I'm expecting to count every child of the relationship, but the query isn't working. How can I make the query work?

You are using the ON statement in the wrong context, it should be WHERE instead:

Select path.ePath, path._rowid, doc.Filenumber, COUNT(doc.ePathUID) AS children
from docPath path LEFT OUTER JOIN
     docMeta doc
     WHERE doc.ePathUID = path._rowid
GROUP BY path._rowid

You have to group by all columns that you have in your select except the ones where you are using aggregation functions. So it should be like :

Select path.ePath, path._rowid, doc.Filenumber, COUNT(doc.ePathUID) AS children
from docPath path LEFT OUTER JOIN
     docMeta doc
     ON doc.ePathUID = path._rowid
GROUP BY path.ePath, path._rowid, doc.Filenumber

For better understanding of why you have to group by all columns in the select list: imagine that you have column ID with vaules 1,1 and Name with David,John . And you will type

select ID, Name from table group by ID

Now you wil group by ID = 1 , so you will get one row with value ID 1 and what value will be in column NAME ? SQL cant just random pick one of the names. So you have to group by both of them

select ID, Name from table group by ID,Name

And the result will be in this case:

ID NAME 
1   David 
1   John

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