编写MySQL数据库查询时出现问题

| 我的SQL数据库中有两个表:
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
获得
name
type
田地。 我以以下方式编写查询:
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;
但是,当我尝试执行它时,出现以下错误:   错误1064(42000):您的SQL语法有错误;检查与您的MySQL服务器版本相对应的手册以获取正确的语法,以在\'附近使用(并在环境如潮湿的环境中选择no)作为U,在第1行的T.no = U.no \' 谁能告诉我如何重新编写查询以避免这种错误?     
已邀请:
您不能使用AND来构造查询结果,它是一个逻辑运算符。您可以通过以下方式获得所有名称,类型,气候,土壤和灌溉组合:
select c.name, c.type, e.climate, e.soil, e.irrigation
from crop c, environment e
where c.no = e.no; 
    
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
    
您可以不使用子选择而做同样的事情,这会更快:
SELECT `T`.`name` 
FROM `enviornment` AS `U` 
    , `crop` AS `T`
WHERE `U`.`climate` LIKE \'wet\'
    AND `U`.`no` = `T`.`no`
    
您应该在
from
子句中的表之间使用逗号,而不是
and
。您已经忘记了字符串“ 10”周围的撇号。 从子选择中选择没有意义,您应该直接从表中选择:
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
拼写错误,应为should15ѭ。     
user711934,尽管很高兴有人演示如何重写查询,但我还是建议您多做一些教程或购买一本有关与联接有关的SQL查询的书,以学习基础知识。 您不应该依赖效率较低的子查询。 我建议做这些教程 http://www.sql-tutorial.net/ 具体通过这些连接示例 http://www.sql-tutorial.net/SQL-JOIN.asp http://beginner-sql-tutorial.com/sql-query-tuning.htm 希望对您有所帮助     

要回复问题请先登录注册