在相当复杂的JOIN中重复列名称

时间:2012-10-08 20:59:06

标签: mysql join duplicates

所以我有一个相对复杂的MySQL查询,它提供了一个重复列,原因是我无法确定。我对SQL有点新鲜。

该查询应该与“ticket”数据库一起加入“问题”条目列表,特别是特定id的最新票证。因此,我有一个内部查询,它自己执行JOINticket以获取最新的票证。这工作正常。然后我尝试使用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_datatime_stamp - 我只获得idticket_id列。当然,这首先打败了加入的目的。

2 个答案:

答案 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;