简体   繁体   English

MySQL内部联接使用

[英]MySQL INNER JOIN USE

I have two tables: 我有两个表:

+-----------------------+
| Tables_in_my_database |
+-----------------------+
| orders                | 
| orderTaken            | 
+-----------------------+

In orders, there are attributes like orderId , orderName . 在订单中,有一些属性,例如orderIdorderName
In orderTaken, there are attributes like userId , orderId and orderStatus . 在orderTaken中,有一些属性,如userIdorderIdorderStatus

Basically, the mechanism of my project is running like: 基本上,我项目的机制运行如下:
A user with a unique userId will be able to take an order from the web page, where each order has its own unique orderId as well. 具有唯一userId的用户将能够从网页上获得订单,其中每个订单也具有自己的唯一orderId After taken, the orderTaken table will record the userId, orderId and initially set orderStatus = 1 . 采取之后, orderTaken表将记录userId, orderId并初始设置orderStatus = 1

Now, I want to select the orders taken by one user where the orderStatus = 1 , but also I will need the orderName from my orders table to be shown. 现在,我想选择一个用户在orderStatus = 1采取的订单,但是我也需要显示订单表中的orderName。 I've learned inner join and written a query as this: 我已经学会了内部联接并编写了这样的查询:

SELECT * FROM orders
WHERE orders.orderId IN
(SELECT orderId FROM orderTaken
WHERE orderTaken.userId = '8' AND orderTaken.orderStatus = '1')
INNER JOIN orderTaken ON orders.orderId = orderTaken.orderId

However, MySQL keeps complaining about syntax error. 但是,MySQL一直抱怨语法错误。 I guess I cannot use inner join this way? 我想我不能以这种方式使用内部联接? Can anybody correct me? 有人可以纠正我吗? Thanks! 谢谢!

SELECT * FROM orders
INNER JOIN orderTaken ON orders.orderId = orderTaken.orderId
WHERE orderTaken.userId = '8' AND orderTaken.orderStatus = '1'

You have over complicated it. 您已经太复杂了。 This will work. 这将起作用。

I have left the quotes in for the userId since I assumed that's right, but if they are of data type INT then you should remove them. 自从我认为正确之后,我就在userId保留了引号,但是如果它们的数据类型为INT ,则应将其删除。

If you want some reading on JOIN s then see these links 如果您想阅读JOIN请参阅以下链接

Try like this 这样尝试

SELECT * 
   FROM (orders INNER JOIN ordersTaken ON orders.orderId = orderTaken.orderId) 
   WHERE orderId IN 
    (SELECT orderId 
     FROM orderTaken 
     WHERE orderTaken.userId = '8' AND orderTaken.orderStatus = '1')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM