Reputation: 33
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?
Upvotes: 0
Views: 1867
Reputation: 8349
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.
Upvotes: 9
Reputation: 564
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
.
Upvotes: 1