我是初学者,我很难理解它的制作方法。 请帮帮我。
catbook
+----+---------+------------+
| id | cat_num | count_book |
+----+---------+------------+
| 1 | 55555 | 21 |
| 2 | 77777 | 40 |
+----+---------+------------+
userbook
+----+-----------+--------------+------------+
| id | user_name | cat_userbook | read_count |
+----+-----------+--------------+------------+
| 1 | Andy | 55555 | 3 |
| 2 | Andy | 77777 | 5 |
| 3 | Tom | 55555 | 4 |
| 4 | Tom | 77777 | 8 |
+----+-----------+--------------+------------+
代码
<?php
require_once("config.php");
$user_name = "Andy";
$sql ="SELECT cat_userbook, read_count, count_book FROM userbook, catbook WHERE user_name LIKE '" . $user_name . "'";
$result = mysqli_query($db_connect, $sql);
$response = array();
while ($row = mysqli_fetch_assoc($result)) {
$response[] = $row;
}
echo json_encode($response);
mysqli_close($db_connect);
结果:
[
{"cat_userbook":"55555","read_count":"3","count_book":"21"},
{"cat_userbook":"55555","read_count":"3","count_book":"40"},
{"cat_userbook":"77777","read_count":"5","count_book":"21"},
{"cat_userbook":"77777","read_count":"5","count_book":"40"}
]
但我想要这个结果,因为这对我来说是必要的:
[
{"cat_userbook":"55555","read_count":"3","count_book":"21"},
{"cat_userbook":"77777","read_count":"5","count_book":"40"}
]
答案 0 :(得分:1)
如果你这样加入:userbook,catbook 你得到userbook x catbook
我认为你在寻找的是:
SELECT cat_userbook, read_count, count_book FROM userbook LEFT JOIN catbook ON catbook.catNum = userbook.cat_userbook WHERE user_name LIKE '" . $user_name . "'";