gpt4 book ai didi

mysql - 哪个 MySQL 查询最适合从两个表中获取数据

转载 作者:行者123 更新时间:2023-11-30 00:32:02 25 4
gpt4 key购买 nike

我有两个这样的表:

mysql> desc table1;
+-------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(255) | NO | | NULL | |
+-------+--------------+------+-----+---------+----------------+
2 rows in set (0.00 sec)

mysql> desc table2;
+-------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+-------+
| id | int(11) | NO | | NULL | |
| name | varchar(255) | NO | | NULL | |
| age | int(11) | NO | | NULL | |
+-------+--------------+------+-----+---------+-------+
3 rows in set (0.00 sec)

两个表中各自数据的 ID 字段相同。

数据库引擎:MYISAM

我想从两个表中获取数据,并且我一直在尝试各种查询。,

以下所有查询都可以正常工作,但我想知道在性能方面最好的查询,表包含超过 2000 万条记录。

查询 1

SELECT t2.age, t1.name
FROM table2 t2
LEFT JOIN table1 t1 ON t2.id = t1.id
WHERE t1.id =1
AND t2.id =1

查询 2

SELECT table1.name, age
FROM table1, table2
WHERE table1.id =1
AND table2.id =1

查询3

SELECT  table1.name , table2.age 
FROM table1, table2
WHERE table1.id = 1
AND table2.id = 1

查询 4

SELECT table1.name, table2.age
FROM table1
INNER JOIN table2 ON table1.id = table2.id
WHERE table1.id =1
AND table2.id =1

查询 5

SELECT table1.name, age
FROM table1, table2
WHERE table1.id =1
AND table2.id =1

那么哪一个最适合高负载/流量网站?性能最佳?

谢谢

最佳答案

如果您想从两个表中获取数据,并且仅在 id = 1 时获取数据,则可以使用 limit 1 而不是 WHERE table1.id =1 AND table2.id =1.

如果您想要获取数据,如果 2 个表中存在相同的 id,您应该INNER JOIN 您的表

SELECT t2.age, t1.name
FROM table2 t2
INNER JOIN table1 t1 ON t2.id = t1.id
LIMIT 1

SELECT t2.age, t1.name
FROM table2 t2, table 1
WHERE t1.id = t2.id
LIMIT 1

关于mysql - 哪个 MySQL 查询最适合从两个表中获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22433829/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com