MySQL SELECT查询与另一个SELECT

时间:2017-06-19 06:01:09

标签: mysql select

我有下一个sql查询:

SELECT CONCAT(v.p_sery, v.p_id) AS sery,
   (SELECT COUNT(1) FROM v where p_delivery_result = 1) AS delivery_count,
   (SELECT COUNT(1) FROM v where p_delivery_result = 2) AS ND1,
   (SELECT COUNT(1) FROM v where p_delivery_result = 3) AS ND2,
   (SELECT COUNT(1) FROM v where p_delivery_result = 4) AS ND3,
   (SELECT COUNT(1) FROM v where p_delivery_result = 5) AS ND4,
   (SELECT COUNT(1) FROM v where p_delivery_result = 6) AS ND5,
   (SELECT COUNT(1) FROM v where p_delivery_result = 7) AS ND6,
   (SELECT COUNT(1) FROM v where p_delivery_result = 8) AS ND7
FROM (
   SELECT p_sery, p_id, d.p_delivery_result 
   FROM registries AS a, registry_regulations r, delivery d
   WHERE a.p_id = r.registry_id AND d.p_id = r.regulation_id AND (SELECT 
   STR_TO_DATE(a.p_date_created, '%Y-%m-%d') BETWEEN '2017-04-01' AND '2017-06-01')
) as v;     

但这不起作用。
错误:Table v doesn't exist 我做错了什么?

我有这张桌子:
enter image description here

我希望获得表格交付中其中一个状态的计数

2 个答案:

答案 0 :(得分:0)

按V之前删除

FROM (
   SELECT p_sery, p_id, d.p_delivery_result 
   FROM registries AS a, registry_regulations r, delivery d
   WHERE a.p_id = r.registry_id AND d.p_id = r.regulation_id AND (SELECT 
   STR_TO_DATE(a.p_date_created, '%Y-%m-%d') BETWEEN '2017-04-01' AND '2017-06-01')
   )  v

答案 1 :(得分:0)

您无法从相关子查询的上下文中访问派生表。请尝试此查询:

SELECT CONCAT(v.p_sery, v.p_id) AS sery,
       COUNT(CASE WHEN p_delivery_result = 1 THEN 1 END) AS delivery_count,
       COUNT(CASE WHEN p_delivery_result = 2 THEN 1 END) AS ND1,
       COUNT(CASE WHEN p_delivery_result = 3 THEN 1 END) AS ND2,
       COUNT(CASE WHEN p_delivery_result = 4 THEN 1 END) AS ND3,
       COUNT(CASE WHEN p_delivery_result = 5 THEN 1 END) AS ND4,
       COUNT(CASE WHEN p_delivery_result = 6 THEN 1 END) AS ND5,
       COUNT(CASE WHEN p_delivery_result = 7 THEN 1 END) AS ND6,
       COUNT(CASE WHEN p_delivery_result = 8 THEN 1 END) AS ND7
FROM (
   SELECT p_sery, p_id, d.p_delivery_result 
   FROM registries AS a
   JOIN registry_regulations r ON a.p_id = r.registry_id 
   JOIN delivery d d.p_id = r.regulation_id
   WHERE STR_TO_DATE(a.p_date_created, '%Y-%m-%d') 
            BETWEEN '2017-04-01' AND '2017-06-01') as v;  

注意:始终使用现代的显式 JOIN语法,而不是旧式的隐式语法。