gpt4 book ai didi

sql-server - SQL查询: Obtaining Rows where Columns A in Table A = Column A in Table B

转载 作者:行者123 更新时间:2023-12-03 09:51:40 24 4
gpt4 key购买 nike

我可能在这里太厚了。

我有一个包含原因代码列表的表,对这些原因的“访问”受到列中是否包含 1 或 0 的限制。

ID | Category | Reason | Brand1 | Brand2 | Brand3
1 | Test | That | 1 | 1 | 0
2 | Test2 | This | 0 | 1 | 0
3 | Test3 | Mine | 0 | 0 | 1

用户表

Username | Brand1 | Brand2 | Brand3
User1 | 1 | 1 | 0

基本上,用户 1 应该只能看到他们在用户表的品牌列中具有 1 的原因,他们在原因表的品牌列中具有 1。

用户 1 应该只能看到原因 ID 1 和 2,因为它们在用户表中的品牌 1 中为 1,品牌 2 中为 1。

我只想返回原因表中的行,其中用户表中的用户在相应的“品牌”列中具有匹配项 1。

用户 1 应返回

ID | Category | Reason | Brand1 | Brand2 | Brand3
1 | Test | That | 1 | 1 | 0
2 | Test2 | This | 0 | 1 | 0

我如何在 SQL 中得到这个,我尝试在 WHERE 语句中用 OR 编写它,但它总是返回每一行。共有7个品牌栏目。

我认为我因为把问题过于复杂化而忽略了一些简单的事情。

干杯

最佳答案

如果你发布你的 SQL,那么我可以得到更接近的信息。

否则:

SELECT *
FROM Reasons AS R
INNER JOIN UserTable AS U
ON (U.Brand1 = 1 AND U.Brand1 = R.Brand1)
OR (U.Brand2 = 1 AND U.Brand2 = R.Brand2)
OR (U.Brand3 = 1 AND U.Brand3 = R.Brand3);

这将仅获取用户拥有该原因也拥有的品牌的行。从技术上讲,您可以更改 U.Brand# = R.Brand#到只是R.Brand# = 1 ,但是其他人以后可能很难阅读。

SELECT *
FROM Reasons AS R
INNER JOIN UserTable AS U
ON (U.Brand1 = 1 AND R.Brand1 = 1)
OR (U.Brand2 = 1 AND R.Brand2 = 1)
OR (U.Brand3 = 1 AND R.Brand3 = 1);

这可能比第二个查询更快,但在大多数情况下不足以引起注意。

关于sql-server - SQL查询: Obtaining Rows where Columns A in Table A = Column A in Table B,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36456131/

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