我如何在mysql中获得预览产品和下一个产品? 例如:当前产品是id 7,我想在表p中获得5和8,如何编写sql?
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for `p`
-- ----------------------------
DROP TABLE IF EXISTS `p`;
CREATE TABLE `p` (
`id` int(10) NOT NULL auto_increment,
`products_name` varchar(200) default NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=12 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of p
-- ----------------------------
INSERT INTO `p` VALUES ('1', 'a');
INSERT INTO `p` VALUES ('2', 'b');
INSERT INTO `p` VALUES ('4', 'd');
INSERT INTO `p` VALUES ('5', 'ed');
INSERT INTO `p` VALUES ('11', 'f');
INSERT INTO `p` VALUES ('7', 'gs');
INSERT INTO `p` VALUES ('8', 'd');
INSERT INTO `p` VALUES ('9', 'f');
答案 0 :(得分:4)
SELECT P1.id,
P1.Products_Name
FROM P P1
INNER JOIN
(SELECT max(id)as ID FROM P WHERE id < 7
UNION ALL
SELECT min(id)as ID FROM P WHERE id > 7
)T ON T.ID = P1.ID
ORDER BY P1.ID ASC
答案 1 :(得分:1)
你可以使用HANDLER
来实现这一点,但这不是标准的。顺便说一句,你想要的只有标准SQL。
mysql> HANDLER p OPEN;
Query OK, 0 rows affected (0.00 sec)
mysql> HANDLER p READ `PRIMARY` = (7);
+----+---------------+
| id | products_name |
+----+---------------+
| 7 | gs |
+----+---------------+
1 row in set (0.00 sec)
mysql> HANDLER p READ `PRIMARY` NEXT;
+----+---------------+
| id | products_name |
+----+---------------+
| 8 | d |
+----+---------------+
1 row in set (0.00 sec)
mysql> HANDLER p READ `PRIMARY` PREV LIMIT 1,1;
+----+---------------+
| id | products_name |
+----+---------------+
| 5 | ed |
+----+---------------+