简体   繁体   中英

Php mysql Query two usernames in one row based on id from another table

I am somewhat new to coding and have been trying to write what I thought would be a straightforward sql query. Please help :)

Table 1: Users
id = user idt
username = user name 

Table 2: Orders
orderid = order id
order_to = user id of person buying 
order_from = user id of person selling
oder_details = text

Basically I want to:

"Select Username(from), Username(to), order_details FROM mytables WHERE Order id = 1;" 

And get the result as 1 row, I'm not sure how to proceed. I thought I could do this with concatenation or something... Can anyone help?

You need to use JOIN to link the tables together.

SELECT fu.username AS fromUser, tu.username AS toUser, o.order_details
FROM Orders o
INNER JOIN Users fu
ON fu.id = o.order_to
INNER JOIN Users tu
ON tu.id = o.order_from
WHERE o.orderid = '1';

Because you have two different users that you need the username from, you need to JOIN the Users table twice to get both user's usernames. Each table needs to have it's own alias fu and tu to allow MySQL to differentiate between them. The same goes for the column names in your SELECT statement so that when you fetch the results with PHP, php can differentiate between the two usernames.

You are looking for a JOIN . This can be done with a keyword or through WHERE clauses. For example,

SELECT * FROM Orders JOIN Users ON Orders.order_to=Users.id

The documentation can be found here: http://dev.mysql.com/doc/refman/5.0/en/join.html .

I'll leave it as an exercise to figure out how to JOIN the order_from .

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