[英]Joining 3 tables using SQL using UNION/INNER JOIN to draw data
[英]using SQL JOIN for union of data
我试图使用JOIN运行查询。 所以,我写了以下内容:
SELECT * FROM (SELECT trade_date, trade_time, price, contract_name
FROM test
WHERE contract_name="Z10"
AND trade_date="2010-12-01"
AND trade_time="0900")
AS A JOIN (SELECT trade_date, trade_time, price, contract_name
FROM test
WHERE contract_name="H11"
AND trade_date="2010-12-01"
AND trade_time="0900")
AS B ON (A.trade_date=B.trade_date
AND A.trade_time=B.trade_time);
它运行正常,除了它返回大量的行:
+------------+------------+-------------+---------------+------------+------------+-------------+---------------+
172025 rows in set (0.31 sec)
所以我分别运行了以下2个查询以检查我应该获得多少行,并且从下面它不应该超过1000。
mysql> select count(*)
from test
where contract_name="Z10"
and trade_date="2010-12-01"
and trade_time="0900";
+----------+
| count(*) |
+----------+
| 983 |
+----------+
1 row in set (0.02 sec)
mysql> select count(*)
from test
where contract_name="H11"
and trade_date="2010-12-01"
and trade_time="0900";
+----------+
| count(*) |
+----------+
| 175 |
+----------+
任何人都可以建议我如何编辑我的JOIN以获得所选日期和时间的2个合同的并集。
实际上,如果从同一个表中获取结果,则不需要进行连接。 你可以这样做:
select count(*)
from test
where contract_name in ("H11","z10")
and trade_date="2010-12-01"
and trade_time="0900";
是的,这是将两个表连接在一起时会发生的情况。 因为日期和时间(您的连接条件)匹配每一行,您获得行的乘积 - 983 x 175 = 172025.连接的两个表实际上是同一个表的子集并不重要。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.