如何优化查询?

时间:2014-10-13 12:08:57

标签: mysql

我需要从一个表中选择数据,但需要分两步完成。我尝试使用IN():

SELECT * FROM my_table WHERE CONCAT(field1,'|',field2) IN 
     (
          SELECT CONCAT(field1,'|',field2) 
          FROM my_table WHERE field3=12345 AND field4=0
     )

但它工作得很慢。如何正确实现?

更新:首先我需要从my_table中选择符合条件的所有行' field3 = 12345 AND field4 = 0'。其次,我需要选择具有相同field1和field2的所有行。

2 个答案:

答案 0 :(得分:1)

您可以在JOIN中拥有多个条件:

SELECT * 
FROM my_table mt
JOIN 
     (
          SELECT DISTINCT field1,,field2
          FROM my_table WHERE field3=12345 AND field4=0
     ) AS q
ON mt.field1 = q.field1 AND mt.field2 = q.field2;

子查询需要DISTINCT,因此我们在结果中不会有双打。

答案 1 :(得分:1)

以你的人为例......

create table person (
   person_id int primary key,
   person_name varchar(20), 
   person_hair varchar(20) 
);

insert into person values (1,'bob','brown'); 
insert into person values (2,'jim','brown'); 
insert into person values (3,'travis','blonde'); 
insert into person values (4,'ron','red'); 

mysql> select * from person where person_name='bob' and person_hair='brown';
+-----------+-------------+-------------+
| person_id | person_name | person_hair |
+-----------+-------------+-------------+
|         1 | bob         | brown       |
+-----------+-------------+-------------+
1 row in set (0.00 sec)

mysql> select * from person where person_name='bob' or  person_hair='brown';
+-----------+-------------+-------------+
| person_id | person_name | person_hair |
+-----------+-------------+-------------+
|         1 | bob         | brown       |
|         2 | jim         | brown       |
+-----------+-------------+-------------+
2 rows in set (0.00 sec)

mysql> select   *
    -> from     person as p1
    -> where    p1.person_hair in (select  person_hair
    ->                             from    person
    ->                             where   person_name='bob');
+-----------+-------------+-------------+
| person_id | person_name | person_hair |
+-----------+-------------+-------------+
|         1 | bob         | brown       |
|         2 | jim         | brown       |
+-----------+-------------+-------------+
2 rows in set (0.03 sec)