mysql版本5.7.39查询问题条件与上重复

wfsdck30  于 2023-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(121)

大家好,我需要帮助

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产品到我的wishlistData其中userID不存在或更新如果存在使用ON DUPLICATE KEY UPDATE但在这里如果id产品存在于wishlistData不更新i代码这但不工作

$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'));";
rnmwe5a2

rnmwe5a21#

第一次感谢重播
这是我的愿望清单表

| userID   | wishlistData   |
| -------- | -------------- |
| 1        | ["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]','$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'));";

相关问题