仅当选定值具有最新日期时,MySql查询

时间:2014-06-12 10:16:43

标签: mysql date

我需要MySql的特殊查询。这是我的实际查询:

SELECT t.accountingClerk, t.creationDate. u.windowsAccountName, t.customer, c.lastName, c.firstName, c.assignee 
FROM ticket as t 
LEFT JOIN customer AS c on t.customer = c.customerId 
LEFT JOIN user AS u ON c.assignee = u.emailAdress 
WHERE c.assignee IS NOT NULL AND t.accountingClerk = 'user1@mail.com'
GROUP BY t.customer;

到目前为止查询工作正常,但结果并不完全是我需要的。有两种可能的匹配票,一种较新的" user2@mail.com"以及使用user1@mail.com作为accountingClerk的旧版本。我需要我的查询才能显示结果,如果' user1@mail.com"是具有最新creationDate的票证的accountingClerk。

我希望你们明白我的意思。

2 个答案:

答案 0 :(得分:0)

您可以尝试这样的事情: -

SELECT t.accountingClerk, t.creationDate. u.windowsAccountName, t.customer, c.lastName,
       c.firstName, c.assignee 
FROM ticket as t 
LEFT JOIN customer AS c on t.customer = c.customerId 
LEFT JOIN user AS u ON c.assignee = u.emailAdress 
WHERE c.assignee IS NOT NULL 
AND t.accountingClerk = (SELECT accountingClerk 
                         FROM tickets
                         WHERE creationDate = (SELECT MAX(creationDate) 
                                               FROM tickets)
                         ) AS Table1
GROUP BY t.customer;

查询可能没有优化,但我希望它对您有用。

答案 1 :(得分:0)

这是我的问题的解决方案:

CREATE TEMPORARY TABLE IF NOT EXISTS tempDateSort AS (SELECT accountingClerk, creationDate, customer FROM ticket ORDER BY creationDate DESC);
CREATE TEMPORARY TABLE IF NOT EXISTS tempCustomerGroup AS (SELECT * FROM tempDateSort GROUP BY customer);
SELECT t.accountingClerk, u.windowsAccountName, t.customer, c.lastName, c.firstName, c.assignee FROM tempCustomerGroup AS t 
LEFT JOIN customer AS c on t.customer = c.customerId 
LEFT JOIN user AS u ON c.assignee = u.emailAdress 
WHERE c.assignee IS NOT NULL AND t.accountingClerk = 'user1@mail.com';