mysql 如何获取在SELECT语句期间获取的不同ID的值?

bvuwiixz  于 2023-01-01  发布在  Mysql
关注(0)|答案(2)|浏览(141)

我创建了一个实体tblPerson,我需要从这个实体获取t.adminID的bGroup和d.personID的bGroup。我尝试了下面的查询,但没有返回任何结果。
'

SELECT t.adminID, p.firstName, p.lastName, t.transID, t.transDate, t.donationID, p.bGroup, b.bankName, d.personID AS 'Donor ID', 'Donor BGroup'
FROM tblTrans t
JOIN tblAdmin a ON t.adminID = a.adminID
JOIN tblPerson p ON a.personID = p.personID
JOIN tblDonation d ON t.donationID = d.donationID
JOIN tblBank b ON d.bankID = b.bankID
WHERE 'Donor BGroup' IN
    (SELECT p.bGroup
    FROM tblPerson p
    JOIN tblDonation d ON p.personID = d.personID
    JOIN tblTrans t ON d.donationID = t.donationID);

'
当我执行子查询时,它会给我d.personID的bGroup,您认为这是怎么回事,可能还有其他选择吗?

示例数据

INSERT INTO tblPerson (personID, firstName, lastName, bGroup)
VALUES ('1A', 'John', 'Doe', 'XY'),
('2A', 'Joe', 'Bishop', 'AB'),
('1B', 'Elly', 'James', 'OP'),
('2B', 'Andre', 'Butch', 'XY'),
('3A', 'Amy', 'Gree', 'AB'),
('3B', 'Alfred', 'Black', 'OP'),
('4C', 'James', 'Brown', 'XY');
    
INSERT INTO tblAdmin (adminID, personID, description)
VALUES (1, '1A', 'Whatever.'),
(2, '1B', ''),
(3, '4C', 'Anything.'),
(4, '1A', '');

INSERT INTO tblDonation (donationID, bankID, personID, donationDate)
VALUES (1, 1, '3B', '2018-12-27'),
(2, 1, '2A', '2022-12-28'),
(3, 2, '3A', '2022-03-23'),
(4, 2, '4C', '2022-06-19'),
(5, 3, '1B', '2022-08-19'),
(6, 3, '2B', '2022-08-08'),
(7, 3, '3B', '2022-07-20'),
(8, 2, '4C', '2022-11-26'),
(9, 1, '3B', '2022-11-26'),
(10, 2, '2A', '2022-01-16');

INSERT INTO tblBank (bankID, bankName)
VALUES (1, 'Bank 1'),
(2, 'Bank 2'),
(3, 'Bank 3');

INSERT INTO tblTrans (transID, transDate, donationID, adminID)
VALUES (1, '2022-12-31', 1, 1),
(2, '2022-01-01', 2, 1),
(3, '2022-05-23', 3, 2),
(4, '2022-05-23', 4, 2),
(5, '2022-07-09', 5, 3),
(6, '2022-08-20', 6 4),
(7, '2022-12-27', 7,4);

Sample ERD Diagram

***预期输出***示例:1,约翰,无名氏,1,2022年12月31日,1,XY,银行1,3B,OP。

7lrncoxx

7lrncoxx1#

WHERE 'Donor BGroup' IN (SELECT...)子句的计算结果为WHERE false,因为tblPerson.bGroup中没有任何行具有该值。因此,SELECT语句的结果集为空。
从你的问题中很难弄明白你的要求。

ff29svar

ff29svar2#

我设法找到了解决方案。因为我需要用不同的ID调用同一个表两次,所以我必须创建两个别名并两次JOIN该表,如下所示:

SELECT t.adminID, person.firstName, person.lastName, t.transID, t.transDate, t.donationID, person.bGroup, b.bankName, donor.personID AS 'Donor ID', donor.bGroup AS 'Donor BGroup'
FROM tblTrans t
JOIN tblAdmin a ON t.adminID = a.adminID
JOIN tblPerson person ON a.personID = person.personID
JOIN tblDonation d ON t.donationID = d.donationID
JOIN tblPerson donor ON 
JOIN tblBank b ON d.bankID = b.bankID;

相关问题