提问人:Rami Nasfi 提问时间:6/16/2023 最后编辑:ShadowRami Nasfi 更新时间:6/16/2023 访问量:33
MySQL 版本 5.7.39 查询问题条件与重复
mysql version 5.7.39 query problem condition with on duplicate
问:
嗨,大家好,我需要帮助
create table wishlist
(
userID int null,
wishlistData longtext collate utf8mb4_bin not null,
constraint userID
unique (userID),
constraint whishlist_user_id_fk
foreign key (userID) references user (id)
);
首先我这样做了,但它在 wishlistData 中产生了重复值
$query = "INSERT INTO wishlist (userID, wishlistData)
VALUES ($userID, JSON_ARRAY('$productId'))
ON DUPLICATE KEY UPDATE wishlistData = JSON_ARRAY_INSERT(wishlistData, '$[0]', '$productId');";
将 id 产品插入到 my wishlistData,其中 userID 不存在,或者使用 ON DUPLICATE KEY UPDATE 更新(如果存在),但在这里,如果 id 产品存在于 wishlistData 上,则不更新 我对此进行了编码,但不起作用
$query = "INSERT INTO wishlist (userID, wishlistData)
VALUES ($userID, JSON_ARRAY('$productId'))
ON DUPLICATE KEY UPDATE wishlistData = JSON_ARRAY_INSERT(wishlistData, '$[0]', IF ((SELECT JSON_SEARCH(JSON_EXTRACT(wishlistData, '$'), 'one', '$productId') IS Not NULL),wishlistData,'$productId'));";
答:
0赞
Rami Nasfi
6/16/2023
#1
首先感谢您重播
这张“我的愿望清单”表
| userID | wishlistData |
| -------- | -------------- |
| 1 | ["90","92"] |
| 2 | ["65","192"] |
对于此代码
$query = “INSERT INTO wishlist (userID, wishlistData) 值 ($userID, JSON_ARRAY('$productId')) ON DUPLICATE KEY UPDATE wishlistData = JSON_ARRAY_INSERT(wishlistData, '$[0]', '$productId');“;
输入 1:$productId=100 userID=1
结果 1 = 预期 1:
| userID | wishlistData |
| -------- | ------------------------|
| 1 | ["100", "90", "92"] |
| 2 | ["65", "192"] |
输入 2:$productId=90 userID=1
结果 2:
| userID | wishlistData |
| -------- | ------------------------ |
| 1 | ["90", "100", "90", "92"]|
| 2 | ["65", "192"] |
预期2:
| userID | wishlistData |
| -------- | --------------------- |
| 1 | ["100", "90", "92"] |
| 2 | ["65", "192"] |
但是第二个代码甚至没有插入
$query = "INSERT INTO wishlist (userID, wishlistData)
VALUES ($userID, JSON_ARRAY('$productId'))
ON DUPLICATE KEY UPDATE wishlistData = JSON_ARRAY_INSERT(wishlistData, '$[0]', IF ((SELECT JSON_SEARCH(JSON_EXTRACT(wishlistData, '$'), 'one', '$productId') IS Not NULL),wishlistData,'$productId'));";
评论