0

我有一个相当复杂的查询,我想与 Zend Framework 一起使用。为了做到这一点,我需要将查询从子查询转换为连接。

这是交易:我有 3 个表需要连接才能形成正确的信息。这可以使用以下查询来完成:

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

我尝试将其转换为连接:

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

但是这样就丢失了有关 0 张照片的信息。

我尝试了许多不同的方法都无济于事...

4

2 回答 2

0

您需要将 GROUP BY 用于聚合函数。根据定义,左连接是外连接,您无需指定。

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
于 2012-07-14T00:51:34.243 回答
0

那是因为 p.location_id = ol.locations_id,将这个条件从 where 移到 join 子句,它应该可以工作。目前它在 where 子句中在 join 评估后应用,因此对于 0 张照片,这个条件结果是 p.location_id = null ,这是错误的,因此行被过滤掉。

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 
于 2012-07-13T19:11:02.967 回答