所以我有一个相对复杂的MySQL查询,它提供了一个重复列,原因是我无法确定。我对SQL有点新鲜。
该查询应该与“ticket”数据库一起加入“问题”条目列表,特别是特定id
的最新票证。因此,我有一个内部查询,它自己执行JOIN
表ticket
以获取最新的票证。这工作正常。然后我尝试使用JOIN
数据库problem
这个内部选择,但是,我得到一个重复列名id
,尽管这是我加入的列名。我的理解是,当你加入一个特定的列时,它不应该“重复”为重复...
无论如何,查询:
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;
正如我所说,如果我这样做:
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
我得到了每个id
的最新票证表。
我尝试解决此问题的一件事是SELECT MAX.* FROM (
,而不只是SELECT * FROM (
。这消除了重复的列名称错误,但内部查询不再返回任何other_data
或time_stamp
- 我只获得id
和ticket_id
列。当然,这首先打败了加入的目的。
答案 0 :(得分:1)
尝试使用AS
为联接查询中的所有列添加别名,就像您为MAX(ticket_id)
字段所做的那样。
例如:
INNER JOIN (
SELECT id AS cur_id, ticket_id as cur_ticket_id ... etc
答案 1 :(得分:1)
将id列别名如下:
SELECT * FROM `problem` P
LEFT JOIN (
SELECT * FROM (
SELECT id AS max_id, MAX(ticket_id) AS ticket_id
FROM `ticket`
WHERE ticket_status = 'o'
GROUP BY max_id
) AS MAX
INNER JOIN (
SELECT id AS cur_id, ticket_id, other_data, time_stamp FROM `ticket`
) CUR ON MAX.max_id = CUR.cur_id AND MAX.ticket_id = CUR.ticket_id
) T ON P.id=T.max_id
WHERE
P.since IS NOT NULL;
我在评论中写道,您可以选择所需的列以避免重复,问题作者理解我的意思是外部选择,我在谈论内部选择。希望我写得对,没有测试。
SELECT * FROM `problem` P
LEFT JOIN (
SELECT CUR.id, CUR.ticket_id, CUR.other_data, CUR.time_stamp FROM (
SELECT id, MAX(ticket_id)
FROM `ticket`
WHERE ticket_status = 'o'
GROUP BY max_id
) AS MAX
INNER JOIN (
SELECT id, ticket_id, other_data, time_stamp FROM `ticket`
) CUR ON MAX.max_id = CUR.cur_id AND MAX.ticket_id = CUR.ticket_id
) T ON P.id=T.id
WHERE
P.since IS NOT NULL;