I have two tables that I'm trying to query together. One is a list of registered users. It has a user id number as primary key and a username field. The other is a transaction table that records transactions between registered users. It contains the user id number of the sender, user id number of the receiver, and the amount that was sent. From these two tables I want to get a list of the transactions that have been sent and received by a particular user. I want the username of the sender, username of the receiver and the transaction amount for any record in which one of the username fields is johndoe. I can get a list of ALL transactions like this SELECT t.id, uf.username, ut.username, t.amount FROM users AS uf, users AS ut, transactions AS t WHERE uf.id = t.user_id_from AND ut.id = t.user_id_to ORDER BY t.id DESC Code (markup): But I'm having trouble narrowing this down to a particular user.
Sorry, finally figured it out. If the user id is 63 then I just use this code SELECT t.id, uf.username, ut.username, t.amount FROM users AS uf, users AS ut, transactions AS t WHERE (uf.id = t.user_id_from AND ut.id = t.user_id_to) AND (uf.id = 63 OR ut.id = 63) ORDER BY t.id DESC Code (markup):
Try doing something like this. SELECT transactions.id, transactions.amount, sent_from.username AS sent_to_user, sent_to.username AS sent_from_user FROM transactions INNER JOIN users AS sent_from ON transactions.user_id = sent_from.id INNER JOIN users AS sent_to ON transactions.user_id = sent_to.id WHERE ( transactions.user_id_from = 63 OR transactions.user_id_to = 63 ) Code (markup):