0

我正在尝试编写一个 MySQL 查询,它应该从两个不同的表中选择行。我进行了不同数量的查询,但它们都需要很长时间才能返回结果(> 0.6 秒)。我想要更快的响应。

情况是:

CREATE TABLE `classes` (
   id int(99) auto_increment primary key,
   status INT(1)
)

CREATE TABLE `classes_names` (
   id int(99) auto_increment primary key,
   class_id int(99),
   name VARCHAR(255)
)

假设您应该获取班级中的所有名字,除了您要搜索的名字。例如,我的名字是“John Doe”,所以我们这样搜索我的名字:

SELECT
  classes_names.`id`

FROM
  `classes_names`

INNER JOIN `classes`
  ON `status` = 1

WHERE
  `name`='John Doe'

在此查询中,我的姓名将与我的班级 ID 一起返回。问题是,我希望除了我自己以外的“班级成员”。所以假设我们有这张表:

+------+----------+
| id   | status   |
+------+----------+
|    1 | 1        |
|    2 | 1        |
+------+----------+

+------+----------+---------------+----------+
| id   | class_id | name                     |
+------+----------+--------+-----------------+
|    1 | 1        | John Doe                 |
|    2 | 1        | Alexandra Fito           |
|    3 | 2        | Rico Hasti               |
|    4 | 1        | Lady Gaga                |
+------+----------+--------------------------+

我想用单词“描述”的查询:SELECT class_names.id WHERE SAME CLASS HAS NAME 'John Doe'.返回的行应该是类中的所有成员 - 没有搜索的名称......所以我应该期待的结果是:

+------+----------+---------------+----------+
| id   | class_id | name                     |
+------+----------+--------+-----------------+
|    2 | 1        | Alexandra Fito           |
|    4 | 1        | Lady Gaga                |
+------+----------+--------------------------+

太好了……有人想试一试吗?去吧!

4

4 回答 4

2

这应该有效:

SELECT a.name, 
       b.class_id 
FROM   classes_names a 
       INNER JOIN (SELECT id, 
                          class_id 
                   FROM   classes_names 
                   WHERE  name = 'John Doe') b 
               ON b.class_id = a.class_id 
                  AND a.id <> b.id 

结果

| 姓名 | CLASS_ID |
-----------------------------------------
| 亚历山德拉菲托 | 1 |
| 嘎嘎小姐 | 1 |

查看演示

于 2013-02-28T21:58:23.607 回答
1
SELECT * FROM classes_names 
WHERE class_id IN (
     SELECT id FROM classes_names 
     WHERE name = "John Doe")
AND name != "John Doe"

我应该指出我不明白指出这status一点,因为那不在您的“英语查询”中。

最好的英文翻译是:

“选择与class_idJohn Doe 所在班级的班级中的任何人,而不是 John Doe。”

于 2013-02-28T21:57:48.077 回答
0
SELECT
  classes_names.`id`

FROM
  `classes_names`

Left JOIN `classes`
  (SELECT class_id
FROM classes_names
WHERE name LIKE "John Doe"
) the_class ON classes_names.class_id = the_class.class_id


WHERE
  `status`=1 and
  `name`NOT LIKE'John Doe'
于 2013-02-28T21:55:01.807 回答
0
SELECT classes_names.id
FROM classes_names

INNER JOIN (
    SELECT class_id
    FROM classes_names
    WHERE name LIKE "John Doe"
) class_john_doe 
ON (
    classes_names.class_id = class_john_doe.class_id
    AND class_john_doe.id != classes_names.id
)

为了提高性能,您应该在 classes_names.class_id 和 classes.id 上设置索引

于 2013-02-28T21:55:09.403 回答