我有以下查询:
select a.clei, a.partNumber,
(
SELECT count(*) FROM
( SELECT * from search_upload_data s where a.clei is not null AND a.clei = s.clei
UNION
SELECT * from search_upload_data s where a.partNumber is not null AND a.partNumber = s.partNumber
) as t1
) as total
from api_analytics_data a
抛出错误:
Error Code: 1054. Unknown column 'a.clei' in 'where clause'
我猜MySQL不允许在内部SQL中使用连接引用,但我不确定如何解决这个问题。
我需要来自search_upload_data的计数,请参阅SQL小提琴:http://sqlfiddle.com/#!9/172ac/2
< ============================================= ============================>
附加说明
我需要弄清楚如何使用UNION执行此操作。每个人的答案中的OR条件都是小规模的,但是在实际数据库中存在很多数据。
这是解释(对于Rajat的回答):
答案 0 :(得分:1)
试试这个
select a.clei, a.partNumber,
( SELECT COUNT(1) As Total
from search_upload_data s
where ( a.clei is not null AND a.clei = s.clei )
OR (a.partNumber is not null AND a.partNumber = s.PartNumber)
) as t1
from api_analytics_data a
答案 1 :(得分:1)
无论如何,这与您想要的输出相对应。只需使用常规OR来选择 clei或partnumber 。
select a.clei, a.partNumber,
(
SELECT count(*) FROM search_upload_data s WHERE
(a.clei is not null AND a.clei = s.clei) OR
(a.partNumber is not null AND a.partNumber = s.partNumber)
) as Total
from api_analytics_data a
答案 2 :(得分:1)
尝试:简单加入OR
和GROUP BY
SELECT a.clei,
a.partNumber,
COUNT(1) tot
FROM api_analytics_data a
LEFT JOIN search_upload_data s ON (a.clei = s.clei OR a.partNumber = s.partNumber)
AND (a.clei is not null OR a.partNumber is not null)
GROUP BY a.clei, a.partNumber
答案 3 :(得分:-1)
select a.clei, a.partNumber,
(
SELECT count(s.id) FROM search_upload_data s where (a.clei is not null AND a.clei = s.clei) OR (a.partNumber is not null AND a.partNumber = s.partNumber)
) as Total
from api_analytics_data a
立即尝试