[英]Joining two tables having two same columns
I am making a school project with mysql database.我正在用 mysql 数据库制作一个学校项目。
Having this table ready, I need to create a query that will join ReciverID and SenderID with accounts.Email column.准备好此表后,我需要创建一个查询,将 ReciverID 和 SenderID 与 accounts.Email 列连接起来。 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 PS:我不建议命名列日期......这是一个通常会导致错误的关键字
EDIT编辑
Base on @HoneyBadger comment the comma joining style is out dated... So here's another way to do it基于@HoneyBadger 评论,逗号连接样式已过时......所以这是另一种方法
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.