简体   繁体   English

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

[英]Why does using an alias inside a “JOIN (SELECT)” statement result in an error?

I'm using MySQL 5.5.16 我正在使用MySQL 5.5.16

I have the following query, which works just fine all by itself. 我有以下查询,它本身就可以正常工作。

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

However, when I include it in aa larger query, I get an error Column 'date' in where clause is ambiguous . 但是,当我将其包含在较大的查询中时, Column 'date' in where clause is ambiguous出现错误Column 'date' in where clause is ambiguous Here is an example where the query above is inside a JOIN : 这是上面的查询在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

Why is it claiming that date is ambiguous? 为什么声称date不明确?

PS I've tried replacing date in the AS date part of the inner query with a inner_date , but that just throws another error Unknown column 'inner_date' in 'where clause' ... PS我试过更换dateAS date与内部查询的一部分inner_date ,但只是抛出另一个错误Unknown column 'inner_date' in 'where clause' ...

You are joining the expiration table, which has a column named date , to the materialised table which itself has a column (from the CASE expression) named date . 您正在将expiration表(具有名为date的列)连接到expiration化表(其本身具有名为date的列(来自CASE表达式))。 You should qualify the use of date in your WHERE clause with the alias of whichever table you were intending to reference. 您应该在WHERE子句中使用要引用的表的别名来限定date的使用。

Either: 或者:

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

Or: 要么:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM