gpt4 book ai didi

php - SQL - IF/ELSE 逻辑取决于表列

转载 作者:行者123 更新时间:2023-11-29 07:16:27 25 4
gpt4 key购买 nike

因此,正如您可能已经猜到的那样,我正在编写一个查询来从数据库中选择数据。而且,正如您可能也猜到的那样,我是用 If/Else 语句的逻辑来编写它的。显然,这在 SQL 中并不像我们希望的那么简单。为了简单地表达逻辑,这里有一些伪代码版本:

SELECT * FROM table1 INNER JOIN table2 on col2 = col1
// Some other JOINS and irrelevant data stuff
if (table2.conditionalColumn == 'x') {
JOIN table3 ON col3 = col2 WHERE a = 1, b = 2, c = 3
} else {
JOIN table3 ON col3 = col2 JOIN table4 ON col4 = col3
}

我知道上面的查询与正确的 SQL 查询没有丝毫相似之处。我试图找出的是如何解决拥有一个列的问题,该列的值决定是联接到一个表还是联接到另一个表。整个概念类似于社交网络的 friend 的 friend 系统。

如有需要,请随时询问有关该问题的任何进一步解释。我尝试使用一些OR逻辑,但我完全陷入困境。我该如何解决这个问题?

谢谢!

编辑 - 为了更容易理解我的目标,我添加了以下场景:

如果用户在 projects_members 表中有一行,或者他们在 中有一行,我想从名为 projects 的表中选择数据team 表,并且该团队在 projects_members 内有一行。 projects_members 中有一个名为 memberType 的列,它设置为“user”或“team”。

最佳答案

将条件移至连接条件内:

SELECT * FROM table1 INNER JOIN table2 on col2 = col1
X JOIN table3 t3 ON (col3 = col2 and table2.conditionalColumn = 'x'
and a = 1 and b = 2 and c = 3)
X JOIN table3 t32 ON (col3 = col2 and table2.conditionalColumn <> 'x')
X JOIN table4 t4 ON (col4 = col3 and table2.conditionalColumn <> 'x')

关于php - SQL - IF/ELSE 逻辑取决于表列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37779721/

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