简体   繁体   中英

Joining two tables having two same columns

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!

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

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