PHP MySQL select 列数组中的数据

PHP MySQL select data where in column array

如果我有一个叫 'invitation' 的 table,像这样:

| invitation_id | sender | recipient             |
| 1             | Josh   | James, Hendry, Max    |
| 2             | Steave | James, Gerrard, Ramon |
| 3             | Steave | Gerrard, Max          |

如果我的名字是 "James",如何显示我收到的邀请数据?

像这样使用:

SELECT *
FROM invitation
WHERE recipient LIKE '%james%'

使用 like %james% 时,如果出现相似的名称,您可能会得到不正确的结果。所以使用find_in_set可以解决你的问题。

select * from invitation where find_in_set('james',recipient) <> 0

你也可以这样使用like

select * from invitation where ',' + recipient + ',' like '%,james,%'

以逗号分隔存储数据(收件人)确实不是一个好习惯。

但您仍然可以使用 find_in_set

您应该 iterate 接收收件人的所有值并这样做

SELECT FIND_IN_SET('James','James,Hendry,Max')

SELECT FIND_IN_SET('James','James, Gerrard, Ramon')

哪个会 return 01

使用LIKE 将有助于搜索。 但是对于这类问题,我们应该使用函数 FIND_IN_SET(),其中 table 中的数据以逗号分隔格式存在。