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. I can only imagine two solutions to do this:
所以现在,我想为PHP数组中的每个ID选择匹配的名称。我只能想象两种解决方案:
1. for-loop:
1. for-loop:
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? 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)?
到目前为止这一切都正确吗?如果是:为什么会这样?如果我有第二个表,MySQL查询会更快吗?只有一张桌子,它非常慢?解决我的问题的最快方法是什么(选择与PHP数组的ID匹配的名称)?
2 个解决方案
#1
2
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:
您可能想阅读这篇文章:
- Passing parameters in MySQL: IN list vs. temporary table
- 在MySQL中传递参数:IN列表与临时表
#2
2
IF you have ID's you should just query the Id's you have. So
如果你有ID,你应该只查询你的ID。所以
$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....) )
#1
2
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:
您可能想阅读这篇文章:
- Passing parameters in MySQL: IN list vs. temporary table
- 在MySQL中传递参数:IN列表与临时表
#2
2
IF you have ID's you should just query the Id's you have. So
如果你有ID,你应该只查询你的ID。所以
$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....) )