[英]SQL Server : get data from another table by joining a table whose ID is active
I am trying to fetch rows of a table suppose table1 by joining another table suppose table2 whose ID are present in one of the two columns of table1 and applying where on table2 with IsActive =1
which is a column in table2 table but I am not able to fetch the proper data.我正在尝试通过加入另一个表假设 table2 来获取表的行,假设 table2 的 ID 存在于 table1 的两列之一中,并在 table2 上应用 where 并且IsActive =1
这是 table2 表中的一列,但我不能获取正确的数据。
Table1 is like below:表1如下:
table1_ID|column_x|column_y
---------+--------+---------
1 |29 |30
2 |30 |31
3 |31 |32
table2 is like:表2就像:
table2_ID|IsActive
---------+--------
29 |1
30 |1
31 |1
32 |0
Now below is my query:现在下面是我的查询:
SELECT
table2.[table2_id],
table2.[column_x],
table2.[[column_y]
FROM
[table2]
WHERE
(table2.[column_x] IN (SELECT table1_id FROM table1 WHERE IsActive = 1)
OR table2.[[column_y] IN (SELECT table1_id FROM table1 WHERE IsActive = 1))
But I get all the rows but I am expecting something like:但我得到了所有的行,但我期待的是:
table1_ID|column_x|column_y
---------+--------+---------
1 |29 |30
2 |30 |31
If I understand your need well, both of this SQL statements should do the work:如果我很好地理解了您的需求,那么这两个 SQL 语句都应该起作用:
SELECT
table1.table1_id,
table1.column_x,
table1.column_y
FROM table1
WHERE table1.column_x IN (SELECT table2_id FROM table2 WHERE IsActive = 1) AND
table1.column_y IN (SELECT table2_id FROM table2 WHERE IsActive = 1)
SELECT
table1.table1_id,
table1.column_x,
table1.column_y
FROM table1
JOIN table2 X ON X.table2_id = table1.column_x
JOIN table2 Y ON Y.table2_id = table1.column_y
WHERE X.IsActive = 1 AND
Y.IsActive = 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.