如何匹配mysql表中存储在一列中的csv?

时间:2014-09-04 00:22:26

标签: mysql

我是mysql的新手

我已经以csv格式存储了用户的兴趣

说person_interests COLUMN存储了多个人的兴趣,比如说

$row['person_interests']='11,22,33,44'

兴趣表11 =音乐,22 =旅行,等等

现在我要列出所有有兴趣11的人,我应该在WHERE子句之后使用什么?

SELECT * FROM persons WHERE ????? 
INNER JOIN
interests 
ON 
persons.person_interest
 =
interests.interest_id
WHERE
interest.interest_id=11

1 个答案:

答案 0 :(得分:0)

在SQL表中存储以逗号分隔的数据是个坏主意。您应该使用多对多关系表来保存它。它使搜索和修改数据变得更加复杂,匹配值无法使用索引,因此查询效率低下。

但如果您坚持使用它,可以使用FIND_IN_SET来匹配它们。

SELECT *
FROM persons AS p
INNER JOIN interests AS i ON FIND_IN_SET(i.interest_id, p.person_interest)
WHERE i.interest_id = 11

您应该拥有一个关系表,而不是将所有兴趣放在一个列中:

CREATE TABLE person_interests (
    person_id INT NOT NULL, -- Foreign key to persons table 
    interest_id INT NOT NULL, -- Foreign key to interests table
    UNIQUE INDEX (person_id, interest_id),
    INDEX (interest_id)
);