在mutliple表中执行SelectQuery之后删除重复的数据

时间:2018-02-19 07:26:25

标签: java mysql sql

我有三个表[users,projects,scenarios]我需要根据modified Date列获取最新更新项目详细信息,但没有重复值

表格是:

users Table :

enter image description here

project table

enter image description here

scenario Table

enter image description here

我尝试下面的查询,但如果使用group by,则返回重复值,然后旧值出现,但我需要最新值

不分组查询

SELECT
    p.`PROJECT_NAME`,
    p.`CREATED_DATE`,
    s.`MODIFIED_DATE`
FROM
    `projects` p
JOIN `scenarios` s ON
    s.`PROJECT_ID` = p.`PROJECT_ID`
WHERE
    P.`USER_ID` =(
    SELECT
        USER_ID
    FROM
        users
    WHERE
        EMAIL = 'test@gmail.com'
)
ORDER BY
    s.`MODIFIED_DATE`
DESC

输出: enter image description here

分组查询:

SELECT
    p.`PROJECT_NAME`,
    p.`CREATED_DATE`,
    s.`MODIFIED_DATE`
FROM
    `projects` p
JOIN `scenarios` s ON
    s.`PROJECT_ID` = p.`PROJECT_ID`
WHERE
    P.`USER_ID` =(
    SELECT
        USER_ID
    FROM
        users
    WHERE
        EMAIL = 'test@gmail.com'
)
group by p.PROJECT_NAME
ORDER BY
    s.`MODIFIED_DATE`
DESC

输出:enter image description here

1 个答案:

答案 0 :(得分:0)

您可以使用子查询单独获取每个项目的最新方案,然后生成的行将再次连接以获取其他列(如果需要)。

SELECT  p.PROJECT_NAME,
        p.CREATED_DATE,
        s.MODIFIED_DATE
        -- all columns in s.* will have the latest row
FROM    projects p
        INNER JOIN scenarios s
            ON  p.PROJECT_ID = s.PROJECT_ID
        INNER JOIN
        (
            SELECT  project_ID, MAX(modified_date) MAX_modified_date
            FROM    scenarios
            GROUP   BY project_ID
        ) t ON s.project_ID = t.project_ID
                AND s.modified_date = t.MAX_modified_date
        INNER JOIN users u
            ON P.USER_ID = u.USER_ID
WHERE   u.EMAIL = 'test@gmail.com'
ORDER   BY s.MODIFIED_DATE DESC

但是,如果您不需要获取其他列,则可以直接使用MAX()GROUP BY

SELECT  p.PROJECT_NAME,
        p.CREATED_DATE,
        MAX(s.MODIFIED_DATE) AS MAX_MODIFIED_DATE
FROM    projects p
        INNER JOIN scenarios s
            ON  p.PROJECT_ID = s.PROJECT_ID
        INNER JOIN users u
            ON P.USER_ID = u.USER_ID
WHERE   u.EMAIL = 'test@gmail.com'
GROUP   BY p.PROJECT_NAME,
            p.CREATED_DATE
ORDER   BY MAX_MODIFIED_DATE DESC