使用JSON_CONTAINS方法时,无法使用JOIN获取category_id信息。如何将其转换为单个查询? 谢谢。
数据库
categories
categories_id categories_title categories_parent_id (JSON) categories_sef_url
1 a {"top": "0"} a
2 b {"top": "0"} b
3 c {"top": "0"} c
4 aa {"id": ["1"], "top": "1"} aa
5 bb {"id": ["2"], "top": "2"} bb
6 cc {"id": ["3"], "top": "3"} cc
7 aaa {"id": ["1", "4"], "top": "4"} aaa
8 bbb {"id": ["2", "5"], "top": "5"} bbb
9 ccc {"id": ["3", "6"], "top": "6"} ccc
SQL
$categories_id = 0;
$sql = "SELECT categories_id from categories where categories_sef_url='aa' ";
$data = $query = $conn->query($sql, PDO::FETCH_ASSOC);
if (!empty($data)) {
foreach($data as $row) {
$categories_id = $row->categories_id;
break;
}
}
$sql = "SELECT categories_id, categories_title from categories where **JSON_CONTAINS(categories_parent_id, '{\"id\":\"".$categories_id."\"}')** OR categories_id='".$categories_id."'";
$data = $query = $conn->query($sql, PDO::FETCH_ASSOC);
if (!empty($data)) {
foreach($data as $row) {
echo $row->categories_id;
echo "<br>";
echo $row->categories_title;
echo "<hr>";
}
}
结果
4
aa
7
aaa