简体   繁体   中英

MySQL INNER JOIN USE

I have two tables:

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

In orders, there are attributes like orderId , orderName .
In orderTaken, there are attributes like userId , orderId and orderStatus .

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. After taken, the orderTaken table will record the userId, orderId and initially set 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. 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. 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.

If you want some reading on JOIN s then see these links

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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