简体   繁体   English

MySQL:联接(2 个表)与单个查询(1 个表)

[英]MySQL: Join (2 tables) vs single queries (1 table)

In PHP , I have an array of 11 persons where just the ID of each person is given:PHP中,我有一个由 11 人组成的数组,其中只给出了每个人的 ID

$persons = array(1, 3, 39, 72, 17, 20, 102, 99, 77, 2, 982);

In my MySQL database , there's a table containing detailed information about each person:在我的MySQL 数据库中,有一个包含每个人详细信息的表格:

TABLE personInfo
 - ID (integer)
 - name (string)
 - birth date (timestamp)
 - weight (decimal)
 - ...

PROBLEM:问题:

So now, I want to select the matching name for each ID in the PHP array .所以现在,我想select 为 PHP 数组中的每个 ID 匹配名称 I can only imagine two solutions to do this:我只能想象两种解决方案来做到这一点:

1. for-loop: 1.for循环:

foreach ($persons as $person) {
    $result = mysql_query("SELECT name FROM personInfo WHERE id = ".$person);
}

2. logical operator OR 2. 逻辑运算符 OR

$result = mysql_query("SELECT name FROM personInfo WHERE id = 1 OR id = 3 OR id = 39 OR ...");

Both solutions are slow , aren't they?两种解决方案都很慢,不是吗?

But if I had another MySQL table containing the IDs of the PHP array...但是,如果我有另一个 MySQL 表,其中包含 PHP 数组的 ID...

TABLE ids
 - ID (integer)

... I could use a join to make a really fast MySQL query , right? ...我可以使用连接来进行非常快速的 MySQL 查询,对吗?

$result = mysql_query("SELECT a.ID, b.name FROM ids AS a JOIN personInfo AS b ON a.ID = b.ID");

QUESTION:问题:

Is all this correct so far?到目前为止,这一切都正确吗? If yes: Why is this so?如果是:为什么会这样? The MySQL query is faster if I have a second table?如果我有第二张表,MySQL 查询会更快吗? With only one table it is incredibly slow?只有一张桌子它非常慢? What is the fastest way to solve my problem (selecting the names matching the IDs of the PHP array)?解决我的问题的最快方法是什么(选择与 PHP 阵列的 ID 匹配的名称)?

IF you have ID's you should just query the Id's you have.如果您有 ID,您应该只查询您拥有的 ID。 So所以

 $result = mysql_query("SELECT name FROM personInfo WHERE id = 1 OR id = 3 OR id = 39 OR ...");

would be right, although I would use会是对的,虽然我会用

$result = mysql_query("SELECT name FROM personInfo WHERE id IN (1,2,3,4....) )

If you have lots of ids (several hundreds or more), feeding the values into a temporary table and joining it is actually faster.如果您有很多 id(数百个或更多),将值输入临时表并加入它实际上更快。

You may want to read this article:您可能想阅读这篇文章:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM