MySQL从这三个表中查询数据的最佳方法

时间:2013-03-02 03:37:40

标签: mysql join

来请你帮忙。请考虑下表,并提供以下数据:

DROP SCHEMA IF EXISTS `jointest`;
CREATE SCHEMA `jointest`;
USE `jointest`;

CREATE TABLE x ( id INT PRIMARY KEY AUTO_INCREMENT , field VARCHAR(20));
CREATE TABLE z ( id INT PRIMARY KEY AUTO_INCREMENT, field VARCHAR(20));
CREATE TABLE y ( id_x INT, id_z INT, PRIMARY KEY (id_x, id_z) );

INSERT INTO x VALUES (NULL,"Good Morning,"), (NULL,"Good Night,"), (NULL,"Bye");
INSERT INTO z VALUES (NULL, "Dad"), (NULL, "Mom"), (NULL, "Bro!");
INSERT INTO y(id_x, id_z) values(1,1), (1,2), (1,3), (2,1), (2,2), (3,3);

是否有更好的解决方案来查询表x,z中的数据?我会附近的东西

SELECT x.field, z.field
FROM y
  INNER JOIN x ON (y.id_x = x.id)
  INNER JOIN z ON (y.id_z = z.id)
ORDER BY x.id;

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

MySQL有一个内置的Query Optimizer,所以你放置表和连接的顺序并不重要。选择使用哪种类型的联接不是性能问题,而是取决于您希望返回的结果1

在正确的列上添加索引以获得可靠的查询性能也很重要。