为什么在“JOIN(SELECT)”语句中使用别名会导致错误?

时间:2012-10-15 17:25:26

标签: mysql mysql-error-1054 mysql-error-1052 mysql-5.5

我正在使用MySQL 5.5.16

我有以下查询,它本身就可以正常工作。

SELECT DISTINCT i.id, 
CASE WHEN e.date >  '2012-10-16'
THEN e.date
ELSE  '9999-99-99'
END AS date, 
CASE WHEN e.date >  '2012-10-16'
THEN time
ELSE  '99-99-99'
END AS time
FROM items AS i
LEFT JOIN expiration AS e ON ( e.item_id = i.id ) 
WHERE (
(
data >=  '2012-10-16'
AND e.valid=1
)
OR i.never_expires=1
)
AND i.valid=1
ORDER BY date ASC , time ASC 
LIMIT 0 , 10

但是,当我将其包含在更大的查询中时,我收到错误Column 'date' in where clause is ambiguous。以下是上述查询位于JOIN

内的示例
SELECT i.id, i.title, i.never_expires, 
CASE WHEN e.date>  '2012-10-16'
THEN e.date
ELSE  '9999-99-99'
END AS date, 
CASE WHEN e.date >  '2012-10-16'
THEN e.time
ELSE  '99-99-99'
END AS time, i.item_price AS price
FROM items AS i
LEFT JOIN expiration AS e ON ( e.item_id = i.id )
JOIN (
  SELECT DISTINCT i.id, 
  CASE WHEN e.date >  '2012-10-16'
  THEN e.date
  ELSE  '9999-99-99'
  END AS date, 
  CASE WHEN e.date >  '2012-10-16'
  THEN time
  ELSE  '99-99-99'
  END AS time
  FROM items AS i
  LEFT JOIN expiration AS e ON ( e.item_id = i.id ) 
  WHERE (
  (
  data>=  '2012-10-16'
  AND e.valid=1
  )
  OR i.never_expires=1
  )
  AND i.valid=1
  ORDER BY date ASC , time ASC 
  LIMIT 0 , 10
) AS ilist ON (i.id=ilist.id) 
WHERE (
(
date >=  '2012-10-16'
AND e.valid=1
)
OR i.never_expires=1
)
AND i.valid=1
ORDER BY dateASC , time ASC

为什么声称date含糊不清?

PS 我尝试使用date替换内部查询的AS date部分中的inner_date,但这只会引发另一个错误Unknown column 'inner_date' in 'where clause' ...

1 个答案:

答案 0 :(得分:4)

您正在将expiration表(名为date的列)加入到物化表中,该表本身有一个名为CASE的列(来自date表达式) 。您应该使用date子句中的WHERE限定使用您想要引用的表的别名。

或者:

WHERE (
(
ilist.date >=  '2012-10-16'
AND e.valid=1
)

或者:

WHERE (
(
e.date >=  '2012-10-16'
AND e.valid=1
)