Question

I'm using 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 a a larger query, I get an error Column 'date' in where clause is ambiguous. Here is an example where the query above is inside a 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?

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'...

Was it helpful?

Solution

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. You should qualify the use of date in your WHERE clause with the alias of whichever table you were intending to reference.

Either:

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

Or:

WHERE (
(
e.date >=  '2012-10-16'
AND e.valid=1
)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top