MySQL除了子句不起作用

时间:2015-06-19 07:10:00

标签: mysql except

根据客户表和贷款表,我希望找到没有贷款的客户。模式定义如下:

mysql> select  * from customer;
+---------------+-----------------+---------------+
| customer_name | customer_street | customer_city |
+---------------+-----------------+---------------+
| Adams         | Spring          | Pittsfield    |
| Brooks        | Senator         | Brooklyn      |
| Curry         | North           | Rye           |
| Glenn         | Sand Hill       | Woodside      |
| Green         | Walnut          | Stamford      |
| Hayes         | Main            | Harrison      |
| Johnson       | Alma            | Palo Alto     |
| Jones         | Main            | Harrison      |
| Lindsay       | Park            | Pittsfield    |
| Smith         | North           | Rye           |
| Turner        | Putnam          | Stamford      |
| Williams      | Nassau          | Princeton     |
+---------------+-----------------+---------------+
12 rows in set (0.00 sec)

mysql> select  * from borrower;
+---------------+---------+
| customer_name | loan_id |
+---------------+---------+
| Adams         | L16     |
| Curry         | L93     |
| Hayes         | L15     |
| Jackson       | L14     |
| Jones         | L17     |
| Smith         | L11     |
| Smith         | L23     |
| Williams      | L17     |
| Adams         | L19     |
| Adams         | L15     |
| Jones         | L15     |
| Williams      | L23     |
+---------------+---------+
12 rows in set (0.00 sec)

现在,我尝试了查询:select customer_name from customer except select customer_name from borrower;

但我收到错误:

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 'select customer_name from borrower' at line 1

我也试过了difference,但是出现了同样的错误。但union效果很好。

mysql> select  customer_name from customer union select customer_name from borrower;
+---------------+
| customer_name |
+---------------+
| Adams         |
| Brooks        |
| Curry         |
| Glenn         |
| Green         |
| Hayes         |
| Johnson       |
| Jones         |
| Lindsay       |
| Smith         |
| Turner        |
| Williams      |
| Jackson       |
+---------------+
13 rows in set (0.00 sec)

我可能出错的任何建议?

2 个答案:

答案 0 :(得分:0)

你可以尝试:

select customer_name from customer where customer_name not in (select customer_name from borrower);

所以你从没有贷款的客户中选择customer_name。

我没有检查,但可能更容易。

答案 1 :(得分:0)

除了和差异关键字在mysql中不起作用。

即使是庞大的表格,下面的查询还可以更快地为您提供结果。

SELECT cust.customer_name 
FROM customer cust 
LEFT JOIN borrower brw ON brw.customer_name=cust.customer_name 
WHERE brw.customer_name IS NULL;

注意:两个表中都应该有cust_id来连接数据而不是customer_name,并且应该对其进行索引。

相关问题