mysql再次选择WHERE和SELECT

时间:2016-06-06 22:28:35

标签: mysql database

我有两个表Customers和Customer_orders。我试图通过使用Customer表中的Customer_ID来选择客户的订单。

SELECT * FROM Customer_orders WHERE Customer_ID = SELECT ID FROM Customers WHERE Customer_name = 'John Doe'

此代码不起作用。我该怎么做?

3 个答案:

答案 0 :(得分:4)

您需要加入这两个表,然后查询您需要的内容。像这样:

SELECT co.* 
FROM Customer_orders co 
INNER JOIN Customers c ON co.Customer_ID = c.ID 
WHERE c.Customer_name = 'John Doe';

答案 1 :(得分:2)

另一个答案有点复杂 - 它可能会试图向您展示可以解决更棘手问题的解决方案。

首先,它从Customer表中查询John Doe的ID。 其次,它查询Customer_orders表中customer_id等于ID的所有列。

我的解决方案很简单:

SELECT * FROM Customer_orders WHERE Customer_ID in (SELECT ID FROM Customers WHERE Customer_name = 'John Doe')
or
SELECT * FROM Customer_orders WHERE Customer_ID = (SELECT ID FROM Customers WHERE Customer_name = 'John Doe')

通常,ID是Customer表的主键,customer_id应该是Customer_orders的键索引。

使用键索引对单个表进行两次查询比使用连接操作的查询快两倍,尤其是当表有太多行时。

感谢蒂姆纠正我的语法。我很欣赏它。我的英语不好。

答案 2 :(得分:1)

您可以使用join方法(内部/左侧)甚至子查询(但不建议在此问题上使用此方法)

这里的例子

内部联接

SELECT cust_order.* FROM Customer_orders cust_order, Customers cust WHERE cust_order.Customer_ID  = cust.ID AND  cust.Customer_name = 'John Doe'

左连接

SELECT cust_order.* FROM Customer_orders cust_order LEFT JOIN Customers cust ON cust_order.Customer_ID  = cust.ID WHERE cust.Customer_name = 'John Doe'

子查询

SELECT * FROM Customer_orders WHERE Customer_ID   =  (SELECT ID FROM Customers WHERE Customer_name = 'John Doe')

确保您在桌面上只有1个ID如果您想使用子查询,或者如果它有超过1个ID,您可以使用“IN”代替“=”