我需要一些MySQL查询的帮助。
我有这张桌子:
Name | Date | City ------+------------+------ Peter | 2013-04-01 | Berlin Paul | 2013-03-01 | London Peter | 2013-03-01 | New York Peter | 2013-01-28 | Tokio
对于每个名字,我需要表格中的第一个日期和相应的城市。
我试过了:
SELECT Name, MIN(Date) as MD, MIN(City) as CN FROM table GROUP BY Name
但是日期与城市名称不对应,结果是:
Peter, 2013-01-028, Berlin
有人可以给我一个提示吗?
由于
答案 0 :(得分:2)
您需要使用子查询来获取min(date)
name
,然后将name
和date
上的结果加入到您的表中:
SELECT t1.Name,
t1.Date as MD,
t1.City as CN
FROM yourtable t1
inner join
(
select min(date) MinDate, name
from yourtable
group by name
) t2
on t1.name = t2.name
and t1.date = t2.mindate
结果是:
| NAME | MD | CN |
---------------------------------------------------
| Paul | March, 01 2013 00:00:00+0000 | London |
| Peter | January, 28 2013 00:00:00+0000 | Tokio |
答案 1 :(得分:0)
试试这个::
SELECT Name, MIN(Date) as MD, City as CN FROM table GROUP BY Name
答案 2 :(得分:0)
LEFT JOIN
应该提供您想要的结果,而不会使查询过于复杂;
SELECT m1.* FROM myTable m1
LEFT JOIN myTable m2
ON m1.Name = m2.Name
AND m1.`date` > m2.`date`
WHERE m2.Name is NULL
它基本上会选择所有没有旧行同名的行。
NAME DATE CITY
Paul 2013-03-01 London
Peter 2013-01-28 Tokio
答案 3 :(得分:0)
以下是如何做到这一点。
SELECT
m.Name,
m.Date,
m.City
FROM mytable as m
INNER JOIN (select min(date) as LDate, name from mytable group by name) as l
on l.LDate = m.date
and l.name = m.name
group by m.name
输出
Name | Date | City
-----------------------------
Paul | 2013-03-01 | London
Peter | 2013-01-28 | Tokio
答案 4 :(得分:0)
您可以使用IN子句:
SELECT yourtable.*
FROM yourtable
WHERE (Name, Date) IN (SELECT Name, Min(Date)
FROM yourtable
GROUP BY Name)
子查询将为每个名称返回名称及其最短日期。外部查询返回名称和日期对应于子查询返回的行的所有行。