我有2个表订单和客户数据为:
mysql> select * from orders;
+---------+----------------+----------+-------+
| orderid | product | customer | price |
+---------+----------------+----------+-------+
| 292 | sofa | 101 | 6000 |
| 293 | table | 105 | 3000 |
| 294 | table | 104 | 1450 |
| 295 | table | 101 | 1200 |
| 296 | chair | 103 | 800 |
| 297 | dressing table | 104 | 9000 |
| 298 | corner | 102 | 1000 |
| 299 | corner | 102 | 900 |
| 300 | bed | NULL | NULL |
| 301 | door | NULL | NULL |
+---------+----------------+----------+-------+
10 rows in set (0.00 sec)
mysql> select * from customers;
+--------+----------+-----------+
| custid | name | location |
+--------+----------+-----------+
| 101 | jaspreet | New delhi |
| 102 | harpreet | Jalandhr |
| 103 | surjit | Amritsar |
| 104 | harneet | ludhiana |
| 105 | hashar | New Delhi |
| 106 | harneet | NULL |
+--------+----------+-----------+
6 rows in set (0.00 sec)
当我运行内部联接时,它返回以下数据:
mysql> select orders.orderid,customers.name from orders inner join customers where orders.customer=customers.custid;
+---------+----------+
| orderid | name |
+---------+----------+
| 292 | jaspreet |
| 295 | jaspreet |
| 298 | harpreet |
| 299 | harpreet |
| 296 | surjit |
| 294 | harneet |
| 297 | harneet |
| 293 | hashar |
+---------+----------+
8 rows in set (0.00 sec)
但是外部联接并没有在这方面起作用。
mysql> select orders.orderid,customers.name from orders left join customers where orders.customer=customers.custid;
错误1064(42000):您的SQL语法有错误;检查 手册,对应右边的MySQL服务器版本 使用n ear'的语法,其中order.customer = customers.custid'在第1行
有人可以帮我解释这个概念吗?
提前致谢
答案 0 :(得分:4)
您正在寻找ON
而不是WHERE
:
SELECT orders.orderid,
customers.name
FROM orders
LEFT JOIN customers
ON orders.customer = customers.custid;
答案 1 :(得分:3)
JOIN
条件由ON
指定,而不是WHERE
:
SELECT orders.orderid,
customers.name
FROM orders
LEFT JOIN customers
ON orders.customer = customers.custid;
您应该将此与内部和外部联接一起使用。 WHERE
应该用于单个表的条件,而不是条件。
如果没有ON子句的连接执行完整的交叉产品,那么你可以在没有这个内部连接的情况下逃脱,然后WHERE
子句基于对此的测试进行过滤。我不知道为什么,但你不能用外连接做到这一点。