Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

$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:

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:

1. for-loop:

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

2. logical operator 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 ...

TABLE ids
 - ID (integer)

... I could use a join to make a really fast MySQL query, right?

$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)?

like image 786
caw Avatar asked Oct 12 '22 03:10

caw


1 Answers

If you have lots of ids (several hundreds or more), feeding the values into a temporary table and joining it is actually faster.

You may want to read this article:

  • Passing parameters in MySQL: IN list vs. temporary table
like image 125
Quassnoi Avatar answered Oct 14 '22 03:10

Quassnoi