2014-11-05 146 views
-2

我有表SQL連接兩個表與LEFTJOIN

  • table_order
  • PRODUCT_NAME

下面是SQL我要查詢table_order這在輸出的product_id完美的作品,但我需要它顯示它的名字而不是數字。我需要用LEFTJOIN來修改mySQL,以某種方式連接到表product_name,但我不斷收到錯誤。因此,而不是

99 = 15,99 = 16

我需要

99 =名稱1,99 = NAME2

SELECT table_order.order_id, table_order.product_id 
       FROM table_order 
       WHERE table_order.order_id=99 
       ORDER BY table_order.order_product_id 


table table_order 
_________________________ 
order_id | product_id | 
_________________________ 
99  | 15   | 
99  | 16   | 
_________________________ 

table product_name 
___________________________ 
product_id | product_name | 
___________________________ 
15   | name1  | 
16   | name2  | 
___________________________ 

回答

0

您需要像product_id那樣加入表格。

SELECT table_order.order_id, product_name.product_name 
FROM table_order 
    INNER JOIN product_name on table_order.product_id = product_name.product_id 
WHERE table_order.order_id=99 
ORDER BY table_order.product_id 
1

使用

SELECT a.product_id, b.product_name 
    FROM table_order AS a LEFT JOIN product_name AS b ON a.product_id = b.product_id 
    WHERE a.order_id = '99' 
    ORDER BY a.product_id 
0
Select t1.product_id,t2.product_name from table_order as t1 
    inner join(
    select * from product_name 
) as t2 
    on t1.product_id = t2.product_name 
    where t1.product_id = //some Number 

見如果有效的話。

0

如果您需要輸出所有訂單,無論該table_order的產品ID是否與product_table有連接,則需要使用LEFT JOIN。

SELECT o.order_id, p.product_name 
    FROM table_order o 
     LEFT JOIN product_name p ON o.product_id = p.product_id 
    ORDER BY o.product_id 

但是如果你只需要得到存在兩個表中的所有行,你可以使用一個INNER JOIN

SELECT o.order_id, p.product_name 
    FROM table_order o 
     INNER JOIN product_name p ON o.product_id = p.product_id 
    ORDER BY o.product_id