我有下面给出的表foo1
foo1
+----+---------+-----------------+----------------+-------------------+---------------------+
| Id | OrderId | OrderNote | SentSalesmanId | OrderedSalesmanId | ConfirmedSalesmanId |
+----+---------+-----------------+----------------+-------------------+---------------------+
| 2 | 1 | important order | 1 | 2 | 3 |
+----+---------+-----------------+----------------+-------------------+---------------------+
和包含Id,代码和名称的salesman表。
推销员
+----+-------+-------+
| Id | Code | Name |
+----+-------+-------+
| 1 | S1001 | N1001 |
+----+-------+-------+
| 2 | S1002 | N1002 |
+----+-------+-------+
| 3 | S1003 | N1003 |
+----+-------+-------+
正如您在表foo1中看到的那样,有3列(SentSalesmanId,OrderedSalesmanId和ConfirmedSalesmanId)与salesman表相关。
这是我的查询
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);
这是我的预期输出
+----+---------+------------------+------------------+---------------------+-----------------------+
| Id | OrderId | OrderNote | SentSalesmanCode | OrderedSalesmanCode | ConfirmedSalesmanCode |
+----+---------+------------------+------------------+---------------------+-----------------------+
| 2 | 1 | important order! | S1001 | S1002 | S1003 |
+----+---------+------------------+------------------+---------------------+-----------------------+
此查询提供了我想要的内容,但它对大数据的效果很慢。我必须使用JOIN三次到销售员表吗?我不能用一个JOIN写它或者有什么方法更有效吗?
感谢。
答案 0 :(得分:1)
您的查询没有任何问题。这应该很快。如果它变慢,您可能需要确保正确索引表。
SHOW INDEX FROM foo1
SHOW INDEX FROM salesman
如果您可以将它们添加到您的问题中,会很有帮助。然后,我们将为所涉及的字段设置#rows和cardinality。
答案 1 :(得分:0)
查询没有错?使用NO WHERE,ORDER BY的查询。请告诉我们整个查询。当你有时间时,每个SHOW CREATE TABLE table_name和每个SHOW INDEX FROM table_name都会为你提供一两个想法。