这3个查询之间是否有性能差异?

时间:2020-08-07 13:19:44

标签: mysql

我有两个表t1t2如下:

create table t1(
  id int primary key,
  name varchar(10),
  desc varchar(500)
);

create table t2(
  id int primary key,
  tid int foreign key references t1(id),
  code varchar(10)
);

现在,我想从t1查询一些数据,这些数据在t2中具有相关记录,因此我编写了以下三个查询:

-- query1,using in with hard code inside it,n might be more than 100
SELECT * FROM t1 WHERE id IN(tid1,tid2,....tidn);

-- query2,using in with subquery 
SELECT * FROM t1 WHERE id IN(SELECT tid FROM t2);

-- query3,using join
SELECT t1.* FROM t1 JOIN t2 ON t1.id=t2.tid;

现在我想知道哪一个查询性能最好,假设MySQL的版本为 5.1 (也与该版本有关吗?), 预先感谢!

我自己进行了测试,发现它与数据大小有关,不同的大小会给出不同的结果,所以我在这里询问

1 个答案:

答案 0 :(得分:0)

我不确定性能,但是最后一个是更好的,因为大多数数据库在IN CLAUSE中有x个元素的限制。我认为它也是最快的,但是最好进行测试以确认这一点。