簡體   English   中英

SQL如何從多行逗號分隔列表中刪除數字

[英]SQL how to remove a number from comma separated list, on multiple rows

可以說我的數據庫中有一個表,看起來像這樣:

|-------------------------|
| id | numbers            |
|-------------------------|
|  1 | 1,3,5,7            |
|  2 | 2,4,6,8            |
|  3 | 1,2,3,4,5,6,7,6,8  |
|-------------------------|

我要刪除所有在數字列中具有數字4的行,說4。 這是什么sql調用? 我正在使用php和mysql。

使用字符串函數,您可以嘗試編寫以下查詢:

UPDATE
    `table_name`
SET
    `numbers` = TRIM(BOTH ',' FROM REPLACE(CONCAT(',', `numbers`), ',4', ''))
WHERE
    FIND_IN_SET('4', `numbers`);

測試:

SELECT TRIM(BOTH ',' FROM REPLACE(CONCAT(',', '4,2,3,4,5,6,7,6,8,4'), ',4', ''));

結果:

2,3,5,6,7,6,8

為了使其更易理解,我使用了不同的表名和列名。 更好的表設計是

users table
-------------------
id
name
other_columns


roles table
-------------
user_id
role_number

示例數據:

users
--------------
id    name   
1     peter
2     tom


roles 
----------
user_id   role_number
1         1
1         3
1         7
2         2
2         8

使用此設計,您現在可以查詢用戶具有的所有角色,例如:

select r.role_number
from users u
join roles r on u.id = r.user_id
where u.name = 'peter'

或者如果您已經有用戶ID,則

select role_number
from roles
where user_id = 1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM