在下面的查询中,我试图在左外连接中使用第一个表。但是我收到了错误。
SELECT
products.id,
products_cstm.oem_c,
products.mfr_part_num,
products.description,
products.cost,
products.assigned_user_id,
customfields_oo.ans
FROM products
LEFT OUTER JOIN (SELECT COUNT( q.id ) AS ans
, pq.product_id
FROM products_quotes pq
LEFT JOIN quotes q
ON pq.quote_id = q.id
WHERE q.deleted = 0
AND pq.deleted = 0
AND q.stage <> 4
AND (pq.qty_shipped < pq.product_qty)
AND pq.product_id = products.id
GROUP BY pq.product_id
) AS customfields_oo
ON customfields_oo.product_id = products.id
LEFT JOIN products_cstm
ON products.id = products_cstm.id_c
WHERE products.deleted = 0
ORDER BY ans DESC
当我运行查询时,它给出了以下错误:
Error Code : 1054
Unknown column 'products.id' in 'where clause'
在左外连接查询中不允许第一个“products”表。
答案 0 :(得分:1)
您不需要在where语句中包含AND pq.product_id = products.id
。因为你是LEFT JOIN
。所以我觉得这样的事情会奏效:
AND (pq.qty_shipped < pq.product_qty)
GROUP BY pq.product_id) AS customfields_oo
ON customfields_oo.product_id = products.id
LEFT JOIN products_cstm
ON products.id = products_cstm.id_c
WHERE products.deleted = 0
ORDER BY openorder DESC
修改强>
您LEFT JOIN
所在的桌子上不需要COUNT
。你也可以这样做:
SELECT
.....
(
SELECT
COUNT( q.id )
FROM products_quotes pq
LEFT JOIN quotes q
ON pq.quote_id = q.id
WHERE q.deleted = 0
AND pq.deleted = 0
AND q.stage <> 4
AND (pq.qty_shipped < pq.product_qty)
AND pq.product_id = products.id
) AS ans
FROM products
.....
答案 1 :(得分:1)
问题是customfields_oo
是派生表而不是相关子查询。因此,您无法从派生表的定义中引用外部表。在这种情况下,您无法从products
定义中引用外部customfields_oo
表。相反,您必须在dervied表定义之外的On
子句中执行该过滤。
Select products.id,
products_cstm.oem_c,
products.mfr_part_num,
products.description,
products.cost,
products.assigned_user_id,
customfields_oo.ans
FROM products
Left Join (
Select pq1.product_id
, Count( q1.id ) As ans
From products_quotes As pq1
Left Join quotes As q1
On pq1.quote_id = q1.id
Where q1.deleted = 0
And pq1.deleted = 0
And q1.stage <> 4
And pq1.qty_shipped < pq1.product_qty
Group By pq1.product_id
) As customfields_oo
On customfields_oo.product_id = products.id
Left Join products_cstm
On products.id = products_cstm.id_c
Where products.deleted = 0
Order By customfields_oo.ans Desc
现在,您已经在评论中说明这太慢了,因为产品被删除&lt;&gt;可以在派生表中评估0。如果是这种情况,那么只需展开派生表以在外products
表上包含过滤器。
Select products.id,
products_cstm.oem_c,
products.mfr_part_num,
products.description,
products.cost,
products.assigned_user_id,
customfields_oo.ans
FROM products
Left Join (
Select pq1.product_id
, Count( q1.id ) As ans
From products_quotes As pq1
Join products As p1
On p1.products.id = pq1.product_id
Left Join quotes As q1
On pq1.quote_id = q1.id
Where q1.deleted = 0
And pq1.deleted = 0
And q1.stage <> 4
And pq1.qty_shipped < pq1.product_qty
And p1.deleted = 0
Group By pq1.product_id
) As customfields_oo
On customfields_oo.product_id = products.id
Left Join products_cstm
On products.id = products_cstm.id_c
Where products.deleted = 0
Order By customfields_oo.ans Desc