2013-11-29 43 views
0

我如何在mysql中獲得預覽產品和下一個產品?例如: :目前的產品是id 7,我想在表p得到5和8,如何編寫sql?我如何在mysql中獲得預覽產品和下一個產品?

enter image description here

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'); 

回答

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 

sqlFiddle example here

+0

你好,TinTran。 +1好〜! –

+0

感謝Jungsu Heo初學者的問題,但很有趣回答:) –

+0

非常好,非常感謝你 –

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   | 
+----+---------------+ 
+0

我婉得到5和8在一個SQL,怎麼辦? –

相關問題