我必须构建一个SQL SELECT查询。表结构如下:
[ID] [PHONE] [description] [DATE]
[1] [600898367] [main] [2016-01-23]
[2] [600898367] [] [2016-01-24]
[3] [600898367] [] [2016-01-26]
[4] [600898367] [] [2016-01-28]
[5] [662349093] [main] [2016-01-10]
[6] [662349093] [] [2016-01-21]
[7] [662349093] [] [2016-01-30]
[8] [662349093] [] [2016-01-31]
这里有不同的记录,分组在同一个电话号码中。第一个(最早的)出现标有[main]标志。 [main]标志没有两个相同的数字。 我想选择每个[主要]记录,另外一个最年轻的同一个电话号码,所以结果应该给出记录1,4,5,8。
请帮忙。
答案 0 :(得分:3)
使用main
子句为您提供MAX
标记的记录。使用JOIN
获取最新记录,使用UNION ALL
获取其他列。最后,执行-- Get the main records first
SELECT *
FROM tbl
WHERE description = 'main'
UNION ALL
-- Get the most recent records
SELECT b.*
FROM (
SELECT
t.PHONE,
MAX(DATE) AS MaxDate
FROM tbl t
GROUP BY PHONE
) a
INNER JOIN tbl b -- Do a JOIN to get the additional columns
ON b.PHONE = a.PHONE
AND b.DATE = a.MaxDate
组合结果。
urls.each do |url|
# Do Something
sleep([1,2,3,4,5].sample)
end
答案 1 :(得分:1)
试试这个;)
MySQL 5.6架构:
CREATE TABLE table1
(`ID` int, `PHONE` int, `description` varchar(4), `DATE` varchar(11))
;
INSERT INTO table1
(`ID`, `PHONE`, `description`, `DATE`)
VALUES
(1, 600898367, 'main', '2016-01-23'),
(2, 600898367, NULL, '2016-01-24'),
(3, 600898367, NULL, '2016-01-26'),
(4, 600898367, NULL, '2016-01-28'),
(5, 662349093, 'main', '2016-01-10'),
(6, 662349093, NULL, '2016-01-21'),
(7, 662349093, NULL, '2016-01-30'),
(8, 662349093, NULL, '2016-01-31')
;
查询1 :
select t.*
from table1 t
inner join (
select `PHONE`, max(`DATE`) as `DATE` from table1 group by `PHONE`
) t1 on t.`PHONE` = t1.`PHONE` and (t.`DATE` = t1.`DATE` or t.`description` = 'main')
order by t.`ID`
<强> Results 强>:
| ID | PHONE | description | DATE |
|----|-----------|-------------|------------|
| 1 | 600898367 | main | 2016-01-23 |
| 4 | 600898367 | (null) | 2016-01-28 |
| 5 | 662349093 | main | 2016-01-10 |
| 8 | 662349093 | (null) | 2016-01-31 |
答案 2 :(得分:0)
您可以使用以下查询:
SELECT t1.*, t3.*
FROM mytable AS t1
LEFT JOIN (
SELECT PHONE, MAX(date) AS max_date
FROM mytable
GROUP BY PHONE
) AS t2 ON t1.PHONE = t2.PHONE
LEFT JOIN mytable AS t3 ON t1.PHONE = t3.PHONE AND t2.max_date = t3.`date`
WHERE t1.description = 'main'
答案 3 :(得分:0)
使用config.vm.synced_folder "host/dir", "/guset/home/dir"
,我们会先在GROUP BY
和PHONE
进行分组,从而获得4行。
接下来,我们将使用GROUP_CONCAT
创建逗号分隔集。可以采用description
条款,按日期订购电话号码。
最后我们想要从集合中获取第一个项目,我们可以使用SUBSTRING_INDEX
执行此操作。
ORDER BY
答案 4 :(得分:0)
尝试以下查询..
SELECT
A.*
FROM
`old_young` A
INNER JOIN
(SELECT
MIN(`DATE`) AS Res
FROM
old_young
WHERE description = 'main'
GROUP BY PHONE
UNION
ALL
SELECT
MAX(`DATE`) AS Res
FROM
old_young
WHERE description = ''
GROUP BY PHONE) B
ON A.DATE = B.Res ;
检查FIDDLE