我有三张桌子。
图书
此表包含所有书籍及其相关信息。
id title author description
1 Lord of the Rings J.R.R. Tolkien ....
2 A Game of Thrones George R.R. Martin ....
类别
此表包含所有现有图书类别。
id product
1 Science-Fiction
2 Thriller
3 Fantasy
4 Action
5 Adventure
book_category
此表将书表链接到类别表。一本书可以有多个类别。
id book_id category_id
1 1 3
2 1 5
3 2 3
4 2 4
5 2 5
现状
借助LEFT JOIN sql查询,我可以检索所有信息(带有类别的书籍)并在我的页面上显示。
我创建了一个编辑表单,我可以借助多项选择来更改书籍的类别。此选择中每个选项的值是category_id。此表单将类别发布到数组。
问题
我想要的是一个查询来处理已发布的书籍及其添加/删除的类别(在book_category表中)。
目前,我有以下查询根据book_id和类别更新book_category表。但它没有用。谁能帮帮我?
编辑07/11/17:不工作:这只是没有更新的行。查询似乎正在运行,但数据库记录中没有任何更新。
$sql = "MERGE book_category AS target
USING
(SELECT *
FROM ( VALUES
(:book_id, :category_id) AS (bid, cid)
)
) AS source
ON target.book_id = source.bid AND target.category_id = source.cid
WHEN NOT MATCHED BY target THEN
INSERT (book_id, category_id) VALUES (:book_id, :category_id)
WHEN NOT MATCHED BY source THEN
DELETE;";
$stmt = $conn->prepare($sql);
foreach($category_id as $c) {
$stmt->bindValue(':book_id', $id, PDO::PARAM_INT);
$stmt->bindValue(':category_id', $c, PDO::PARAM_INT);
$stmt->execute();
}
编辑08/11/17: 在尝试使用mysqli使其工作时,我收到以下错误:
Notice: Wrong SQL:
MERGE book_category AS target
USING
(SELECT *
FROM ( VALUES (1, 2) AS (bid, cid) )
) AS source
ON target.book_id = source.bid AND target.category_id = source.cid
WHEN NOT MATCHED BY target THEN
INSERT (book_id, category_id) VALUES (1, 2);
Error :
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near
'MERGE book_category AS target USING (SELECT * FROM ( VALUES' at line 1
答案 0 :(得分:0)
如果你在循环中运行1个参数(book_id,category_id):
当源不匹配时,请删除 始终删除除参数之外的所有插入行。 使用
如果不是EXISTS(从book_category中选择1 WHERE book_id = bid AND category_id = cid) INSERT INTO book_category VALUES(book_id,cid)