So I have a relatively complicated MySQL query that is giving a Duplicate Column, for reasons I haven’t been able to determine. I’m somewhat new to SQL.
The query is supposed to join a list of “problem” entries with the database of “tickets,” specifically the latest ticket for the particular id. Thus I have an inner query that executes a JOIN of the ticket table on itself to get the latest ticket. This works correctly. I then attempt to JOIN this inner selection with the problem database, however, I get a Duplicate Column Name id, despite the fact that this is the column name I am joining on. My understanding is that when you join on a particular column, it shouldn’t “count” as duplicate…
Anyway, the query:
SELECT * FROM `problem` P
LEFT JOIN (
SELECT * FROM (
SELECT id, MAX(ticket_id) AS ticket_id
FROM `ticket`
WHERE ticket_status = 'o'
GROUP BY id
) AS MAX
INNER JOIN (
SELECT id, ticket_id, other_data, time_stamp FROM `ticket`
) CUR ON MAX.id = CUR.id AND MAX.ticket_id = CUR.ticket_id
) T ON P.id=T.id
WHERE
P.since IS NOT NULL;
As I said, if I do just this:
SELECT * FROM (
SELECT id, MAX(ticket_id) AS ticket_id
FROM `ticket`
WHERE ticket_status = 'o'
GROUP BY id
) AS MAX
INNER JOIN (
SELECT id, ticket_id, other_data, time_stamp FROM `ticket`
) CUR ON MAX.id = CUR.id AND MAX.ticket_id = CUR.ticket_id
I get a table of the latest ticket for each id.
One thing I have tried to fix this is to SELECT MAX.* FROM ( instead of just SELECT * FROM (. This eliminates the duplicate column name error, but the inner query no longer returns any other_data or time_stamp – I only get the id and ticket_id columns. This defeats the purpose of the join in the first place, of course.
Alias the id column as below:
I wrote in a comment that you could just select the needed columns to avoid the duplicate and the question author understood I meant the external select, I was talking about the inner one. Hope I wrote it right, didn’t test.