0

I have a rather complicated query that I want to put into use with Zend Framework. In order to do this I needed to convert query from subqueries to joins.

This is the deal: I have 3 tables that need to be connected in order to form proper info. This can be accomplished using this query:

SELECT 
 ol.orders_id, 
 ol.photos_to_add, 
 ol.locations_id, 
 l.name, 
 (select 
   count(*) 
  from 
   photos as p 
  where 
   p.location_id = ol.locations_id and p.per_order = ol.orders_id) 
  as added 
FROM `order_has_locations` AS ol, 
 `locations` AS l 
WHERE ol.orders_id = 1 and l.id = ol.locations_id

I try to convert it to joins:

SELECT ol.orders_id, ol.locations_id, ol.photos_to_add, l.name, count(p.id) AS added
FROM order_has_locations as ol
INNER JOIN locations as l on l.id = ol.locations_id
left outer join photos as p on p.per_order = ol.orders_id
where p.location_id = ol.locations_id and ol.orders_id = 1

but this way the info about 0 photos is missing.

I tried many different approaches to no avail...

Johnny_Bit
  • 101
  • 1

2 Answers2

0

That is because of p.location_id = ol.locations_id, move this condition from where to join clause, it should work. As currently it in where clause it is applied after join has evaluated, hence for 0 photos this condition turns out to be p.location_id = null which is false and hence rows are filtered out.

SELECT ol.orders_id, ol.locations_id, ol.photos_to_add, l.name, count(p.id) AS added
  FROM order_has_locations as ol
 INNER JOIN locations as l on l.id = ol.locations_id
  LEFT outer join photos as p on p.per_order = ol.orders_id 
   AND p.location_id = ol.locations_id 
 WHERE ol.orders_id = 1
 GROUP BY ol.orders_id, ol.locations_id, ol.photos_to_add, l.name 
Nitin Midha
  • 2,258
  • 20
  • 22
0

You need to use GROUP BY for aggregate functions. And left join is an outer join by definition, you needn't specify that.

SELECT ol.orders_id, ol.locations_id, ol.photos_to_add, l.name, count(p.id) AS added
FROM order_has_locations as ol
INNER JOIN locations as l on l.id = ol.locations_id
LEFT JOIN photos as p on p.per_order = ol.orders_id
where p.location_id = ol.locations_id and ol.orders_id = 1
GROUP BY p.id
ksiimson
  • 593
  • 3
  • 8