2015-09-06 79 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; 
相关问题