gpt4 book ai didi

mysql - 来自八个表的多个 JOIN 和 SELECT 语句

转载 作者:行者123 更新时间:2023-11-29 08:51:01 25 4
gpt4 key购买 nike

我正在尝试创建一个 SQL 语句,该语句采用八个不同的数字并从一个​​数据库中搜索八个不同的表以获取相应的值。我不断收到无效语法,但我不明白为什么。这是我的代码:

SELECT cable_length.ID, drawing.ID, optional.ID, output_type.ID, pressure_range.ID, pressure_type.ID, series.ID, termination.ID 
FROM
(
SELECT value AS cable_length FROM A1 WHERE A1.id = %s
JOIN SELECT value AS drawing FROM A2 WHERE A2.id = %s,
JOIN SELECT value AS optional FROM A3 WHERE A3.id = %s,
JOIN SELECT value AS output_type FROM A4 WHERE A4.id = %s,
JOIN SELECT value AS pressure_range FROM A5 WHERE A5.id = %s,
JOIN SELECT value AS pressure_type FROM A6 WHERE A6.id = %s,
JOIN SELECT value AS series FROM A7 WHERE A7.id = %s,
JOIN SELECT value AS termination FROM A8 WHERE A8.id = %s
);

%s 将仅更改为数字。每个表中的列名称是“ID”和“Value”。我想按“ID”搜索并返回“值”。表名称为cable_length等。非常感谢任何帮助。

最佳答案

如果您知道所有 8 个值都存在,您可以像这样加入:

SELECT  A1.value as cable_length
, A2.value as drawing
, A3.value as optional
, A4.value as output_type
, A5.value as pressure_range
, A6.value as pressure_type
, A7.value as series
, A7.value as termination
FROM A1, A2, A3, A4, A5, A6, A7, A8
WHERE A1.ID = %s
AND A2.ID = %s
AND A3.ID = %s
AND A4.ID = %s
AND A5.ID = %s
AND A6.ID = %s
AND A7.ID = %s
AND A8.ID = %s

如果您不知道这一点,但可以保证第一个值存在,那么您的查询会变得更加丑陋,因为您需要左联接。

SELECT  A1.value as cable_length
, A2.value as drawing
, A3.value as optional
, A4.value as output_type
, A5.value as pressure_range
, A6.value as pressure_type
, A7.value as series
, A7.value as termination
FROM A1
LEFT JOIN A2
ON A2.ID = %s
LEFT JOIN A3
ON A3.ID = %s
LEFT JOIN A4
ON A4.ID = %s
LEFT JOIN A5
ON A5.ID = %s
LEFT JOIN A6
ON A6.ID = %s
LEFT JOIN A7
ON A7.ID = %s
LEFT JOIN A8
ON A8.ID = %s
WHERE A1.ID = %s

如果没有保证存在任何值,则破解方法是使用一个子查询 UNION ALL的 8 个查询返回 8 列,其中仅填充一列,然后选择 MAX每列的名称作为该列名称。

这是一个糟糕的技巧,我过去曾用过它来避免许多偶尔加入的左连接出现性能问题。

顺便说一句,名为 A1..A8 的 8 个表表明您需要有数据库经验的人来检查您的设计并为您提供更好的布局。

关于mysql - 来自八个表的多个 JOIN 和 SELECT 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11228938/

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