我有两个MySQL表,名称为accounts
id username role
1 pete101 2
2 JohnnyA 1
3 Anno65 1
4 tom 1
5 koala3 2
并且名称为事件
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表格中显示角色为'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
它显示accounts表的ID的两倍,但我想要下一个回显:
id date username accountID
2 10-04-20 koala3 5
5 10-04-20 pete101 1
所以第一列是events表的ID,最后一列(accountID)是accounts表的ID
我该怎么做才能解决此问题?
非常感谢!
尝试
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 |用户名|日期|帐户ID-:| :------- | :--------- | :--------2 | koala3 | 2010-04-20 | 55 | pete101 | 2010-04-20 | 1个
db <>小提琴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>";
}