2011-04-17 85 views
0

查询我有我的SQL数据库的两个表:问题写MySQL数据库

mysql> select *from crop; 
+------+-----------+----------+ 
| no | name  | type  | 
+------+-----------+----------+ 
| 1 | pineapple | fruits | 
| 2 | wheat  | mainFood | 
| 1 | apple  | fruits | 
| 2 | corn  | main  | 
| 3 | rose  | flower | 
| 2 | wheat  | main  | 
| 2 | maize  | main  | 
| 1 | drydates | fruits | 
+------+-----------+----------+ 

mysql> select *from enviornment; 
+---------+------------+----------+------+ 
| climate | irrigation | soil  | no | 
+---------+------------+----------+------+ 
| humid | medium  | alluvial | 2 | 
| humid | medium  | black | 1 | 
| humid | medium  | red  | 1 | 
| sunny | low  | black | 1 | 
| sunny | medium  | alluvial | 1 | 
| wet  | high  | red  | 2 | 
| humid | low  | red  | 3 | 
+---------+------------+----------+------+ 

我想从crop table得到nametype领域,根据气候,土壤和灌溉。

我写我的查询以下列方式:

mysql> select T.name from((select name from crop)as T and (select no from envior 
nment where climate like wet)as U)where T.no=U.no; 

但是,当我试着执行它时,我得到以下错误:

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'and (select no from enviornment where climate like wet)as U)where T.no=U.no' at line 1

谁能告诉我如何重新写我的查询,以避免这个错误?

回答

1

不能使用构造查询结果,这是一个logical operator。你可以得到所有名称,类型,气候,土壤和灌溉组合:

select c.name, c.type, e.climate, e.soil, e.irrigation 
from crop c, environment e 
where c.no = e.no; 
+0

非常感谢快速答复... :) – user711934 2011-04-17 08:48:08

1
select T.name 
from (select name from crop) as T 
inner join (select no from enviornment where climate like wet) as U 
on T.no = U.no 
0

你可以做同样的,而不使用子查询,这将是更快:

SELECT `T`.`name` 
FROM `enviornment` AS `U` 
    , `crop` AS `T` 
WHERE `U`.`climate` LIKE 'wet' 
    AND `U`.`no` = `T`.`no` 
0

您应该from条款,不and在表之间用逗号。你已经忘记了串'wet'周围的撇号。

有从子查询的选择没有意义的,你应该直接从表中选择:

select 
    T.name, T.type 
from 
    crop as T, 
    enviornment as U 
where 
    T.no = U.no and U.climate = 'wet' 

时下联接使用join命令通常做法:

select 
    T.name, T.type 
from 
    crop as T, 
    inner join enviornment as U on T.no = U.no 
where 
    U.climate = 'wet' 

注:您的表名enviornment拼写错了,应该是environment