我正在尝试编写一个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 |
+------+----------+--------------------------+
Sooo ......有人想试一试吗?去吧!
答案 0 :(得分: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
<强>结果强>
| NAME | CLASS_ID | ----------------------------- | Alexandra Fito | 1 | | Lady Gaga | 1 |
答案 1 :(得分:1)
SELECT * FROM classes_names
WHERE class_id IN (
SELECT id FROM classes_names
WHERE name = "John Doe")
AND name != "John Doe"
我应该指出我不明白指出status
位,因为那不在你的“英文查询”中。
这个最好的英文翻译是:
“选择John Doe所在班级class_id
的班级中的任何人,而不是John Doe。”
答案 2 :(得分: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'
答案 3 :(得分: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
上设置索引