2
我有一個表main_table,它包含輸入和輸出的記錄。從同一個表中選擇特定的sql
id | type | time | joiner
1 out 2014-10-15 12:00:00 1
2 in 2014-10-15 13:00:00 1
3 out 2014-10-15 14:00:00 1
4 out 2014-10-15 15:00:00 1
5 in 2014-10-15 16:00:00 1
6 out 2014-10-15 17:00:00 1
當我加入,其結果是:
SELECT
t1.id as id_out, t1.time as time_out, t2.id as id_in, t2.time as time_in
FROM
(SELECT * FROM main_table WHERE type = "out") as t1
LEFT JOIN
(SELECT * FROM main_table WHERE type = "in") as t2
ON t1.joiner = t2.joiner AND t1.id < t2.id
GROUP BY
t1.id
id_out | time_out | id_in | time_in | ....
1 2014-10-15 12:00:00 2 2014-10-15 13:00:00
3 2014-10-15 13:00:00 5 2014-10-15 16:00:00
4 2014-10-15 15:00:00 5 2014-10-15 16:00:00
6 2014-10-15 17:00:00 NULL NULL
,我需要跳過第二排,因爲記錄id = 5必須在那裏只有一次。 PS:'joiner'是必須的,因爲這裏只有一個值,但它會有更多的值。
Here is SQL for create table and insert records
CREATE TABLE IF NOT EXISTS `main_table` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`type` enum('in','out') NOT NULL,
`time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`joiner` int(2) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=8 ;
INSERT INTO `main_table` (`id`, `type`, `time`, `joiner`) VALUES
(1, 'out', '2014-10-15 10:00:00', 1),
(2, 'in', '2014-10-15 11:00:00', 1),
(3, 'out', '2014-10-15 12:00:00', 1),
(4, 'out', '2014-10-15 13:00:00', 1),
(5, 'in', '2014-10-15 14:00:00', 1),
(6, 'out', '2014-10-15 15:00:00', 1);
你的問題是什麼?只想要time_out和time_in具有值的行嗎? – Arion 2014-10-17 08:55:06