SQL JOIN:如何回显 table A 列的值与 table B 列同名?

SQL JOIN: How to echo values of a column of table A with same name as a column of table B?

我有两个 MySQL table 名称为 帐户

id username role
1  pete101  2
2  JohnnyA  1
3  Anno65   1
4  tom      1
5  koala3   2

并使用名称 events

id date     accountID
1  02-04-20 3
2  10-04-20 5
3  07-04-20 4
4  10-04-20 2
5  10-04-20 1

现在我想在 HTML table 中显示角色为“2”的帐户中日期为“10-04-20”的所有事件。 我为此使用此查询:"SELECT * FROM events JOIN accounts ON events.accountID = accounts.id WHERE events.date = '10-04-20' AND accounts.role = '2'"

while($row = mysqli_fetch_array($result)){   
    echo "<tr><td>" . $row['id'] . "</td><td>" . $row['date'] . "</td><td>" . $row['username'] . "</td><td>" . $row['accountID'] . "</td><br>"; 
}

此查询(和 PHP)的结果是下一个:

id  date     username accountID
5  10-04-20  koala3   5
1  10-04-20  pete101  1

它显示了两次 帐户的 ID table 但我想要下一个 echo:

id  date     username accountID
2  10-04-20  koala3   5
5  10-04-20  pete101  1

所以第一列是 events table 的 ID,最后一列 (accountID) 是 accounts[=40] 的 id =] table

我该怎么做才能解决这个问题?

非常感谢!

尝试

CREATE TABLE accounts
    (`id` int, `username` varchar(7), `role` int)
;
    
INSERT INTO accounts
    (`id`, `username`, `role`)
VALUES
    (1, 'pete101', 2),
    (2, 'JohnnyA', 1),
    (3, 'Anno65', 1),
    (4, 'tom', 1),
    (5, 'koala3', 2)
;
✓

✓
CREATE TABLE events
    (`id` int,  `date` date, `accountID` varchar(10))
;
    
INSERT INTO events
    (`id`, `date`, `accountID`)
VALUES
    (1, '02-04-20', 3),
    (2, '10-04-20', 5),
    (3, '07-04-20', 4),
    (4, '10-04-20', 2),
    (5, '10-04-20', 1)
;
✓

✓
SELECT 
e.id,a.username,e.`date`, e.accountID
FROM events e JOIN accounts a ON e.accountID = a.id 
 WHERE e.date = '10-04-20' AND a.role = '2'
Order BY e.id
id | username | date       | accountID
-: | :------- | :--------- | :--------
 2 | koala3   | 2010-04-20 | 5        
 5 | pete101  | 2010-04-20 | 1        

db<>fiddle here

既然对评论有帮助,不妨做个回答。将其从 $row['colname']; 更改为 $row

中的实际位置

更改原始查询:

while($row = mysqli_fetch_array($result)){   
    echo "<tr><td>" . $row['id'] . "</td><td>" . $row['date'] . "</td><td>" . $row['username'] . "</td><td>" . $row['accountID'] . "</td><br>"; 
}

为此:

while($row = mysqli_fetch_array($result)){   
    echo "<tr><td>" . $row[0] . "</td><td>" . $row[1] . "</td><td>" . $row[2] . "</td><td>" . $row[3] . "</td><br>"; 
}