![](/img/trans.png)
[英]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.