0

我如何在 1 个 sql 或 2 个中获得所有兄弟?
哪个更快?哪个对我的网站有好处?
以及如何在一个 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();
    }

?>
4

5 回答 5

1
SELECT * FROM `p` main
LEFT JOIN `p` helper ON helper.categories_id = main.categories_id
WHERE main.id = 3

您可以加入表格以选择数据。据我所知,在大多数情况下,加入表格会更快,但 Yogesh 的回答也是正确的。

于 2013-07-25T06:54:55.340 回答
1

使用左外连接!

select p.id, p.name, p.categories_id from p sql1 left outer join p on sql1.categories_id = p.categories_id where sql1.id = 3 
于 2013-07-25T06:56:02.727 回答
1

查询将是

SELECT * FROM p WHERE categories_id IN (
     SELECT group_concat(categories_id) 
     FROM p 
     WHERE id = 3)

您必须使用子查询来获取第categories_id一个并将其结果传递给上层查询。

于 2013-07-25T06:50:44.327 回答
1

我认为您不会对 2 个查询有任何性能问题。但是您可以通过一个查询选择所需的信息。

SELECT p.*
FROM (
    SELECT categories_id
    FROM p
    WHERE id = 3
) AS cat
LEFT JOIN p ON p.categories_id = cat.categories_id
ORDER BY id ASC;

结果:

+--------+--------+----------------+
| 编号 | 姓名 | 类别ID |
+--------+--------+----------------+
| 1 | 吉米 | 1 |
| 2 | 蒂娜 | 1 |
| 3 | dd | 1 |
| 4 | 你好 | 1 |
| 6 | 懒惰 | 1 |
| 12 | 阿斯达夫 | 1 |
+--------+--------+----------------+
6 行一组(0.00 秒)
于 2013-07-25T07:14:16.363 回答
0

这个简单的代码就可以了

 $select_sql="select * from p where categories_id = id and id=3";
 $result=$db->execute($select_sql);


 while(!$result->EOF){
            echo $result->fields['name'].'<br>';
            $result->MoveNext();
}
    ?>
于 2013-07-25T06:55:17.637 回答