Even in the original query COUNT(TABLE1.FIELD3) AS QTY does not count distinct field3 values, it counts nonnull values, also duplicates.
Also, COUNT always acts on the whole result, not on the separate tables. If you want to join a count done on the separate table3 you could do a subquery SELECT FOREIGNKEY, COUNT(FIELD) FROM TABLE3 GROUP BY FOREIGNKEY as SUBQUERY and JOIN SUBQUERY on the foreign key.
For example you could
Code:
SELECT ORDERS.*, ORDERITEMCOUNT.ItemCount
FROM ORDERS
LEFT JOIN (SELECT ORDERID, COUNT(*) as ItemCount FROM ORDERITEMS GROUP BY ORDERID) ORDERITEMCOUNT
ON ORDERS.ID = ORDERITEMCOUNT.ORDERID
The more usual way would be to simply join ORDERITEMS and apply grouping on the overall result.
So, what do you expect to
count?
Edit: To once more use the orders and order items as example, a query like the following will count as the result field names advertise
Code:
SELECT COUNT(DISTINCT ORDERS.ID) as OrderCount
COUNT(ORDERS.ID) as OrderstimesOrderitemsCount
COUNT(*) as OrderstimesOrderitemsCount
FROM ORDERS
LEFT JOIN ORDERITEMS
ON ORDERS.ID = ORDERITEMS.ORDERID
As ORDERS.ID is never null, you have no difference between COUNT(*) and COUNT(ORDERS.ID) here. I think you expect COUNT(expression) to act as the DISTINCT count but that needs COUNT(DISTINCT expression).
It's unclear whether you want the single rows that will be added, when you join a table3 or whether you only want to join it for a count, then you might use the subquery approach to first compute the count and join only that as 1:1 related data not growing your overall result row count. COUNT(DISTINCT ORDERS.ID) then also is not a solution, it still multiplies all ORDERS rows as many times as each order has order items. Just like the join copies all ORDERS data of the same order id as many times as there are orderitems to be able to add orderitem detail data, the COUNT(DISTINCT ORDERS.ID) is also repeated orderitems times.
I think you're not very familiar with SQL, neither with how JOINS act, how COUNT acts and how to GROUP BY. So as Tamar asked already, what are you trying to achieve?
Bye, Olaf.