2015-09-06 53 views
0

我有2個表格,現在我想要輸出所有與我在active_season中選擇的季節匹配的表格。當我嘗試下面的查詢時,出現錯誤。有人能幫我嗎?當在其他表格中選擇條件時獲取數據

SELECT * FROM `matches` 
Where season = active_season.season 

錯誤:#1054 - 在 'where子句'

table matches 
id date  season  team_a team_b 

1 2015-08-23 2015-2016 yellow red 
2 2015-04-18 2014-2015 green blue 
3 2015-09-04 2015-2016 white brown 
4 2014-02-11 2013-2014 pink yellow 
5 2015-03-19 2014-2015 red brown 
6 2015-11-30 2015-2016 blue pink   
7 2015-05-06 2014-2015 green white 

table active_season 
id season 
1 2015-2016 
+1

您正在介紹不屬於這組表的一部分的表active_season:(from子句或聯接)。數據庫引擎就像是,這是從哪裏來的? – Drew

+0

http://www.w3schools.com/sql/sql_join.asp – user2268997

+0

但無論你做什麼,如果你加入,做一個**顯式加入**。這就像是2015年 – Drew

回答

0

是的,它應該錯誤,如你正在做的方式未知列 'active_seasons.season'。你需要做的是什麼樣的

SELECT m.* FROM `matches` m 
JOIN active_season ac ON m.season = ac.season; 

(OR)執行JOIN操作添加表active_seasonFROM條款像

SELECT * FROM `matches`, active_season 
Where season = active_season.season 
0

當您在SELECTWHERE零件的使用表的字段查詢,它必須在FROM部分。將SELECT視爲資源傳遞部分,將WHERE視爲過濾部分,將FROM視爲爲前述部分提供所需資源的資源佔用區域。

現在,當您在FROM部分中使用多個表時,MySQL會返回這些表的一個產品。例如如果你有以下兩個表給出行:

table1 (id, title) 
------------------ 
id title 
------------------ 
1  first 
2  second 

table2 (id, fk_id, description) // fk_id is foreign key from table1 
------------------------------------- 
id fk_id description 
1  1  d1 
2  2  d2 

並運行此查詢

SELECT * FROM table1, table2 

你得到這樣的結果:

id title id fk_id description 
----------------------------------------- 
1  first 1  1  d1 
1  first 2  2  d2 
2  second 1  1  d1 
2  second 2  2  d2 

每記錄針對table2的每個記錄即,即兩個表的乘積。要獲得正確的結果,您需要指定table1的哪個記錄與table2的哪個記錄相匹配。這可以使用條件來完成在WHERE部分或JOIN

SELECT * FROM table1, table2 WHERE table1.id=table2.fk_id 
----------------------------------------- 
id title id fk_id description 
----------------------------------------- 
1  first 1  1  d1 
2  second 2  2  d2 

同樣的結果將使用JOIN

SELECT * FROM table1 JOIN table2 ON table1.id=table2.fk_id 
----------------------------------------- 
id title id fk_id description 
----------------------------------------- 
1  first 1  1  d1 
2  second 2  2  d2 

同樣的問題時,可以通過使用INNER JOIN

SELECT 
    a.* 
FROM 
    `matches` a 
    JOIN active_season b ON a.season = b.season 
WHERE 
    b.season='2015-2016' 
來解決實現

你可以在這裏詳細閱讀關於MySQL連接:https://dev.mysql.com/doc/refman/5.0/en/join.html

+0

雖然這段代碼可能會回答這個問題,但最好也提供一些解釋來解釋你的推理和它的作用。 – nalply

0
SELECT mac.* 
FROM `matches` mac 
JOIN 
     active_season ac 
    ON mac.season = ac.season; 
相關問題