什么MySQL查询会获取booking_id=1
的所有行,但省略第一行和最后一行?
这可以通过查看sequence
列来确定,0始终是第一行,但最后一行是变化的 - 在这种情况下它是4但它可以是2,3,6等。
代码:
CREATE TABLE waypoint
(
id int auto_increment primary key,
booking_id varchar(11),
sequence varchar(11),
address varchar(300)
);
INSERT INTO waypoint
(booking_id, sequence, address)
VALUES
('1', '0', 'MK9 1AN,Santander,Santander Uk Plc,Santander House,201,Grafton Gate East'),
('1', '1', 'MK13 0DD,4,Glyn Street,New Bradwell,Milton Keynes,'),
('1', '2', 'MK6 2DU,65,Towan Avenue,Fishermead,Milton Keynes,'),
('1', '3', 'MK1 1LG,10a,Clarke Road,Bletchley,Milton Keynes,'),
('1', '4', 'MK11 1BJ,3,York Road,Stony Stratford,Milton Keynes');
答案 0 :(得分:1)
使用MIN和MAX功能。 FIDDLER DEMO
SELECT * FROM waypoint
WHERE ID NOT IN(
(SELECT MIN(ID) FROM waypoint),
(SELECT MAX(ID) FROM waypoint)
)
答案 1 :(得分:1)
这是返回所需结果的查询:
SELECT * FROM waypoint
WHERE ID NOT IN(
(SELECT MIN(ID) FROM waypoint WHERE booking_id="1"),
(SELECT MAX(ID) FROM waypoint WHERE booking_id="1")
)
AND booking_id="1";
此查询使用ID
从路标点计算最小值和最大值booking_id="1"
。然后,这些id被排除在结果集(NOT IN
子句)