Home > Back-end >  Joining two tables having two same columns
Joining two tables having two same columns

Time:06-12

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!

CodePudding user response:

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

  • Related