引用具有特定字段的输出表

时间:2015-09-25 04:17:25

标签: mysql sql

我有两张桌子:

Users。其中ID是主键

++++++++++++++++++
+ID......... Name+
+1 ......... Alex+
+2 ......... Rony+
+3 ......... Fred+
++++++++++++++++++

OrderOrder_id是主键,User_Id是外键

Order_Id ............. User_ID ............ Day    
123456   .............    3    ............ Monday
123457   .............    2    ............ Tuesday
123458   .............    1    ............ Friday

现在我想输出order_id = 123458的记录,但是,我不希望输出为:

123458   .............    1    ............ Friday

我希望它显示名称Alex而不是值1

我想这样:

Order_id .............    Name    ............ Day
123458   .............    Alex    ............ Friday

例如,如果我这样做:

SELECT * FROM ORDERS WHERE ORDER_ID = 123458它将显示此输出:

123458   .............    1    ............ Friday

如前所述,我希望显示名称Alex而不是值1

2 个答案:

答案 0 :(得分:2)

正如d_onimic所说,如果你从一个sql教程开始,那就更好了。以下是使用INNER JOIN并为表名

创建as Alias的示例
SELECT O.OrderID, U.Name, O.Day 
FROM ORDERS as O
INNER JOIN Users as U
  ON O.UserID = U.ID
WHERE ORDER_ID = 123458

答案 1 :(得分:-1)

这是答案。如果你有时间,你也可以优化它。我刚刚发布的时间少了。

select Oders_id, Name, Day
from (select *
      from Users,
           Orders
      where Users.uid = Oders.user_id
        and Oders_id=123458).