SQL - 排序左连接和主要结果

时间:2012-01-24 01:35:25

标签: sql sql-order-by left-join

我目前正在尝试从数据库中返回所有工程师。除此之外,还有其他一些用户满意的信息。但是我想让ac表加入最近的行,然后按contactname命令主要结果。

有人能把我拉向正确的方向吗?

SELECT 
    mb.type, mb.contactname, mb.id, mb.inv_addressline2, mb.inv_addressline3, mb.signup_date,
    fb.engineer_id, fb.job_id, fb.neg_or_pos, fb.rating, fb.author_id,
    ac.engineer_id, ac.timestamp, ac.author_id,
    jb.job_id, SUBSTRING(jb.job_description, 0, 200) AS `short_description`, jb.timestamp 
FROM " . MEMBERS_TABLE . " AS mb 
LEFT JOIN " . ACCEPTED . " AS ac ON mb.id = ac.engineer_id 
LEFT JOIN " . FEEDBACK . " AS fb ON ac.job_id = fb.job_id 
LEFT JOIN " . JOBS . " AS jb ON fb.job_id = jb.job_id 
WHERE mb.type = 2 
GROUP BY mb.contactname 
ORDER BY ac.timestamp DESC

2 个答案:

答案 0 :(得分:0)

因此,只选择来自ac的行,其中时间戳是该组的最大值;然后按联系人姓名订购。

这是一个查询,以匹配每位工程师的最大时间戳:

SELECT engineer_id, max(timestamp) as latest
FROM ac
GROUP BY engineer_id;

然后只选择(id,timestamp)在此表中的行。

答案 1 :(得分:0)

最后想出来:

SELECT 
    res.type, res.contactname, res.id, res.inv_addressline2, res.inv_addressline3, res.signup_date,
    res.engineer_id_global, res.job_id_global, res.neg_or_pos, res.rating, res.author_id_global,
    res.timestamp_global, res.job_description               
FROM
    (
        SELECT
            mb.type, mb.contactname, mb.id, mb.inv_addressline2, mb.inv_addressline3, mb.signup_date,
            fb.engineer_id AS `engineer_id_global`, fb.timestamp AS `timestamp_global`, fb.job_id AS `job_id_global`, fb.neg_or_pos, fb.rating, fb.author_id AS `author_id_global`,
            ac.engineer_id, ac.timestamp, ac.author_id,
            jb.job_id, jb.job_description 
        FROM
            " . MEMBERS_TABLE . " AS mb 
        LEFT JOIN
            " . ACCEPTED . " AS ac 
        ON
            mb.id = ac.engineer_id 
        LEFT JOIN 
            " . FEEDBACK . " AS fb 
        ON 
            ac.job_id = fb.job_id 
        LEFT JOIN
            " . JOBS . " AS jb 
        ON 
             fb.job_id = jb.job_id 
        WHERE 
            mb.type = 2 
        ORDER BY
            fb.timestamp DESC
    ) AS res 
GROUP BY 
    res.contactname
ORDER BY
    res.contactname

干杯

修改

以上现在有效!