I have table foo1 which given below
foo1
+----+---------+-----------------+----------------+-------------------+---------------------+
| Id | OrderId | OrderNote | SentSalesmanId | OrderedSalesmanId | ConfirmedSalesmanId |
+----+---------+-----------------+----------------+-------------------+---------------------+
| 2 | 1 | important order | 1 | 2 | 3 |
+----+---------+-----------------+----------------+-------------------+---------------------+
and salesman table which contains Id, Code and Name.
salesman
+----+-------+-------+
| Id | Code | Name |
+----+-------+-------+
| 1 | S1001 | N1001 |
+----+-------+-------+
| 2 | S1002 | N1002 |
+----+-------+-------+
| 3 | S1003 | N1003 |
+----+-------+-------+
As you can see in table foo1 there are 3 columns(SentSalesmanId, OrderedSalesmanId and ConfirmedSalesmanId) related with salesman table.
Here is my query
SELECT
f.Id,
f.OrderId,
f.OrderNote,
s1.Code AS SentSalesmanCode,
s2.Code AS OrderedSalesmanCode,
s3.Code AS ConfirmedSalesmanCode
FROM
foo1 f
INNER JOIN salesman s1 ON (s1.Id = f.SentSalesmanId)
INNER JOIN salesman s2 ON (s2.Id = f.OrderedSalesmanId)
INNER JOIN salesman s3 ON (s3.Id = f.ConfirmedSalesmanId);
Here is my expected output
+----+---------+------------------+------------------+---------------------+-----------------------+
| Id | OrderId | OrderNote | SentSalesmanCode | OrderedSalesmanCode | ConfirmedSalesmanCode |
+----+---------+------------------+------------------+---------------------+-----------------------+
| 2 | 1 | important order! | S1001 | S1002 | S1003 |
+----+---------+------------------+------------------+---------------------+-----------------------+
This query gives what I want, but it works slow for big data. Do I have to use JOIN three times to salesman table? Can't I write it with one JOIN or Is there any way which is more efficient?
Thanks.
EXPLAIN SELECT ....it will tell you why it is slow. This is correct way of joining. How many records do you have?