1

所以我有一个相对复杂的 MySQL 查询,它给出了一个重复的列,原因我无法确定。我对 SQL 有点陌生。

该查询应该将“问题”条目列表与“票证”数据库相结合,特别是特定的最新票证idJOIN因此,我有一个内部查询,它自己执行一个ticket表来获取最新的票。这可以正常工作。然后,我尝试JOIN使用数据库进行此内部选择problem,但是,我得到了 Duplicate Column Name 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列。当然,这首先违背了加入的目的。

4

2 回答 2

1

尝试使用 为连接查询中的所有列指定别名,就像您为该字段AS所做的那样。MAX(ticket_id)

例如:

INNER JOIN (
    SELECT id AS cur_id, ticket_id as cur_ticket_id  ... etc
于 2012-10-08T21:02:51.483 回答
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;
于 2012-10-08T21:03:51.053 回答