不能在子查询中使用别名

时间:2013-04-04 03:46:24

标签: php mysql subquery alias

您好我正在使用两个表来进行一次查询。 我在household_tbl中有municipality和barangay以及household_connector_id字段 但在第二个表中,tbl_household_member只有一个household_connector_id字段。 在子查询上使用的第一个选择的别名不起作用。请帮忙。

以下是查询:

SELECT household_connector_id as h_id,
       barangay as b,
       municipality as m,

(SELECT COUNT(*) FROM household_tbl WHERE municipality = m
AND SUBSTR(expiry_date,1,2) LIKE "04" AND SUBSTR(expiry_date,7,4) LIKE "2013" AND NOT(expiry_date = "") AND NOT(expiry_date = "n/a"))   
+

(SELECT COUNT(*) FROM tbl_household_members WHERE household_connector_id = h_id
AND SUBSTR(expiry_date,1,2) LIKE "04" AND SUBSTR(expiry_date,7,4) LIKE "2013" AND NOT(expiry_date = "") AND NOT(expiry_date = "n/a")) as total

FROM (SELECT DISTINCT * FROM household_tbl) AS TI GROUP BY b

1 个答案:

答案 0 :(得分:1)

您无法引用分配给其他列的别名,因此您需要引用列名称:

SELECT household_connector_id as h_id,
  barangay as b,
  municipality as m,
  (SELECT COUNT(*) 
   FROM household_tbl t
   WHERE t.municipality = TI.municipality  -- changed to column name
    AND SUBSTR(t.expiry_date,1,2) LIKE "04" 
     AND SUBSTR(t.expiry_date,7,4) LIKE "2013" 
     AND NOT(t.expiry_date = "") 
     AND NOT(t.expiry_date = "n/a")) +
  (SELECT COUNT(*) 
   FROM tbl_household_members h
   WHERE h.household_connector_id = TI.household_connector_id   -- changed to column name
    AND SUBSTR(h.expiry_date,1,2) LIKE "04" 
     AND SUBSTR(h.expiry_date,7,4) LIKE "2013" 
     AND NOT(h.expiry_date = "") 
     AND NOT(h.expiry_date = "n/a")) as total
FROM 
(
  SELECT DISTINCT * 
  FROM household_tbl
) AS TI 
GROUP BY barangay