1つのSQLまたは2つのSQLですべての兄弟を取得するにはどうすればよいですか?
どちらがより速いですか?私のサイトに適しているのはどれですか?
1つのSQLでそれを行う方法は?誰でも私のためにこの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,
`name` varchar(200) default NULL,
`categories_id` int(10) default NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=14 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of p
-- ----------------------------
INSERT INTO `p` VALUES ('1', 'jimmy', '1');
INSERT INTO `p` VALUES ('2', 'tina', '1');
INSERT INTO `p` VALUES ('3', 'dd', '1');
INSERT INTO `p` VALUES ('4', 'hello', '1');
INSERT INTO `p` VALUES ('6', 'slucky', '1');
INSERT INTO `p` VALUES ('7', 'asdf2', '223');
INSERT INTO `p` VALUES ('8', 'sdaf3', '22');
INSERT INTO `p` VALUES ('9', '2dfg', null);
INSERT INTO `p` VALUES ('12', 'asdf', '1');
INSERT INTO `p` VALUES ('13', 'dsdf', null);
phpコード:
<?php
// get categories_id first
$select_sql="select * from p where id = 3";
$result=$db->execute($select_sql);
$categories_id = $result->fields['categories_id'];
// get all records has the same categories_id with id = 3
$select_sql="select * from p where categories_id = ".$categories_id;
$result=$db->execute($select_sql);
// output all brother categories
while(!$result->EOF){
echo $result->fields['name'].'<br>';
$result->MoveNext();
}
?>