我正在尝试查找此查询的结果:
SELECT *
FROM Table1
WHERE ColumnX in (SELECT DISTINCT ColumnX FROM Table2
UNION
SELECT DISTINCT ColumnY FROM Table2)
它还使用此查询过滤DateAddedToMarket(Table1中的一列)的结果:
DateAddedToMarket >= '2018-01-01'
AND DateAddedToMarket < '2018-02-01'
ORDER BY DateAddedToMarket DESC
我试过了:
SELECT *
FROM Table1
WHERE ColumnX in (SELECT DISTINCT ColumnX FROM Table2
UNION
SELECT DISTINCT ColumnY FROM Table2)
AND DateAddedToMarket >= '2018-01-01'
AND DateAddedToMarket < '2018-02-01'
ORDER BY DateAddedToMarket DESC
我收到了正确的日期,但也收到了我希望从表2中匹配的值之外的结果。
+--------+--------------+
|ColumnX | ColumnY |
+--------+--------------+
| 872510 | 879962 |
| 872514 | 879963 |
| 872511 | |
| 872515 | |
| 872512 | |
| 879529 | |
| 872513 | |
| 879530 | |
| 879959 | |
| 879960 | |
| 879961 | |
+--------+--------------+
答案 0 :(得分:1)
如果要在子查询表(在本例中为表2)中搜索DateAddedToMarket,则此查询将不起作用。
在这里,主查询从表1中获取数据。表2中找到了ColumnX.因此日期过滤器(DateAddedToMarket)不适用于此。它只是抓住Table1到ColumnX给它的一切......
实际上,如果您尝试在表2中进行搜索,那么此查询将无法实现此目的。你需要这样做:
SELECT * FROM Table1 WHERE ColumnX in (
SELECT DISTINCT ColumnX FROM Table2 WHERE DateAddedToMarket ... UNION
SELECT DISTINCT ColumnY FROM Table2 WHERE DateAddedToMarket ...)
答案 1 :(得分:0)
select子句“IN”函数非常低效,除非查询优化器可以使它成为连接。改变你“in(... union ...)”子句并加入表格。然后在where子句 s 和Union两个几乎相同的选择中添加过滤器。
SELECT Table1.* FROM Table1
JOIN Table2 on Table1.ColumnX = Table2.ColumnX
where Table1.DateAddedToMarket >= '2018-01-01'
AND Table1.DateAddedToMarket < '2018-02-01'
UNION
SELECT Table1.* FROM Table1
JOIN Table2 on Table1.ColumnX = Table2.ColumnY
where Table1.DateAddedToMarket >= '2018-01-01'
AND Table1.DateAddedToMarket < '2018-02-01'
ORDER BY Table1.DateAddedToMarket DESC