Joining two tables having two same columns

Issue

I am making a school project with mysql database.

Having this table ready, I need to create a query that will join ReciverID and SenderID with accounts.Email column. I have tried many solutions, but all my atempts resulted into duplicates or errors. The result should look like this.

I have table "accounts"

CREATE TABLE IF NOT EXISTS `accounts` (
  `AccountID` INT(11) NOT NULL AUTO_INCREMENT,
  `Email` VARCHAR(128) NOT NULL,
  `Password` VARCHAR(128) NOT NULL,
  `Balance` DOUBLE(10, 5) NOT NULL DEFAULT 10,
  `VerifyCode` INT(6) NOT NULL,
  PRIMARY KEY (`AccountID`),
  UNIQUE INDEX `Email_UNIQUE` (`Email`),
  UNIQUE INDEX `VerifyCode_UNIQUE` (`VerifyCode`)
)

And table "transactions"

CREATE TABLE IF NOT EXISTS `mydb`.`transactions` (
  `TransactionID` INT(11) NOT NULL AUTO_INCREMENT,
  `SenderID` INT(11) NOT NULL,
  `ReciverID` INT(11) NOT NULL,
  `Date` INT(32) NOT NULL,
  `Note` VARCHAR(256) NULL DEFAULT NULL,
  `Amount` DOUBLE(10, 5) NOT NULL,
  PRIMARY KEY (`TransactionID`),
  INDEX `Sender_idx` (`SenderID`),
  INDEX `reciver_fk_idx` (`ReciverID`),
  CONSTRAINT `reciver_fk` FOREIGN KEY (`ReciverID`) REFERENCES `accounts` (`AccountID`) ON DELETE NO ACTION ON UPDATE NO ACTION,
  CONSTRAINT `sender_fk` FOREIGN KEY (`SenderID`) REFERENCES `accounts` (`AccountID`) ON DELETE NO ACTION ON UPDATE NO ACTION
)

Thanks for any reply!

Solution

You can try working with alias.

Something like

Select T.TransactionID, S.email, R.email, T.date, T.note, T.Amount 
From Transactions T, Accounts S, Accounts R
Where T.SenderID = S.AccountID AND T.ReceiverID = R.AccountID AND 
--The rest of your conditions

PS: I wouldn’t recommend naming a column date… It’s a key word usually resulting in errors

EDIT

Base on @HoneyBadger comment the comma joining style is out dated… So here’s another way to do it

Select T.TransactionID, S.email, R.email, T.date, T.note, T.Amount 
From Transactions T
Join Accounts S On T.SenderID = S.AccountID
Join Accounts R On T.ReceiverID = R.AccountID 
--add your conditions

Answered By – K-Galalem

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published