SQL Query从一个表中获取数据,其中特定列等于其他表中的值

时间:2015-01-19 04:28:28

标签: mysql

我有两个包含以下列的表(相对于此问题的列的子集)

Name: ORDERS
order_id
order_number
grand_total

Name: PURCHASE_ORDERS
purchase_order_id
order_number
supplier

基本上我正在创建一个搜索功能,可以根据输入过滤出DataGridView中的行,我想知道如何获得一个返回以下内容的查询:

伪代码示例 -

  

从订单中选择* WHERE order_number =(从中选择order_number)   purchase_orders,其中supplier ='test')

有时可以从purchase_orders表格返回多个订单号,这会影响上述查询吗?

2 个答案:

答案 0 :(得分:1)

你应该使用

SELECT* 
   from orders 
WHERE 
   order_number 
IN (SELECT 
       order_number 
    FROM
       purchase_orders 
    WHERE supplier = 'test')

请参阅:http://www.tutorialspoint.com/mysql/mysql-in-clause.htm

答案 1 :(得分:1)

SELECT
    *
FROM
    orders
WHERE order_number IN (SELECT order_number FROM purchase_orders WHERE supplier = 'test')

或更好

SELECT
    *
FROM
    orders
    LEFT OUTER JOIN purchase_orders ON purchase_orders.order_number = orders.order_number
WHERE
    purchase_orders.supplier = 'test'