2

I have two table account, order:

CREATE TABLE `account` (
   `id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
   `name` VARCHAR(50) NULL DEFAULT NULL,
   PRIMARY KEY (`id`)
);
CREATE TABLE `order` (
   `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
   `accout_id_1` INT(10) UNSIGNED NOT NULL DEFAULT '0',
   `accout_id_2` INT(10) UNSIGNED NOT NULL DEFAULT '0',
   PRIMARY KEY (`id`)
);

And now I want get account.name for order acount_id_1 and account_id_2 in order.

SQL 1:

SELECT `order`.id,
   (SELECT account.name FROM account WHERE account.id = order.accout_id_1) AS account_name_1,
   (SELECT account.name FROM account WHERE account.id = order.accout_id_2) AS account_name_2
FROM `order`

SQL 2:

SELECT `order`.id, acc_1.name AS account_name_1, acc_2.name AS account_name_2
FROM `order`
JOIN account acc_1 ON acc_1.id = `order`.accout_id_1
JOIN account acc_2 ON acc_2.id = `order`.accout_id_2

Using PHP:

SELECT account.id, account.name
FROM account;

SELECT *
FROM `order`;

The results above are contained in the array:

$accounts = array(
   1 => 'A',
   2 => 'B'
);

$orders = array(
   0 => array(id => 1, accout_id_1 => 1, accout_id_2 => 1),
   1 => array(id => 2, accout_id_1 => 1, accout_id_2 => 2),
   2 => array(id => 3, accout_id_1 => 2, accout_id_2 => 2)
);

When foreach $orders, i can get account.name in array $accounts with key is $orders.accout_id_1, $orders.accout_id_2:

$accounts[$orders[0]['account_id_1']];

With SQL 1, SQL 2 and Using PHP. How the best performance?

1 Answer 1

2

You should generally try to minimize the amount of data that has to be passed between the SQL server and PHP. If they're not running on the same machine, this can be a big bottleneck, but it's still quite a bit of overhead if they're on the same server.

So try to do as much as possible in the SQL query, i.e. either SQL 1 or SQL 2.

As for choosing between SQL 1 and SQL 2, I think MySQL is generally better at optimizing joins than correlated subqueries, although I've heard that recent versions of MySQL have improved the latter.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.