我在MySQL数据库中有两个表,如下所示:
userid |userid | Username | Plan(VARCHAR) | Status |
-----------+------------+--------------+---------------+---------+
1 | 1 | John | 1,2,3 |1 |
2 | 2 | Cynthia | 1,2 |1 |
3 | 3 | Charles | 2,3,4 |1 |
planid(INT) | Plan_Name | Cost | status |
-------------+----------------+----------+--------------+
1 | Tamil Pack | 100 | ACTIVE |
2 | English Pack | 100 | ACTIVE |
3 | SportsPack | 100 | ACTIVE |
4 | KidsPack | 100 | ACTIVE |
id |userid | Username | Plan | Planname |
---+-------+----------+------------+-------------------------------------+
1 | 1 | John | 1,2,3 |Tamil Pack,English Pack,SportsPack |
2 | 2 | Cynthia | 1,2 |Tamil Pack,English Pack |
3 | 3 | Charles | 2,3,4 |English Pack,Sportspack, Kidspack |
由于计划表中的计划ID是整数,并且用户可以容纳许多计划,因此将其存储为以逗号分隔的varchar形式,因此当我尝试使用IN条件时,它不起作用。
SELECT * FROM plan WHERE find_in_set(plan_id,(select user.planid from user where user.userid=1))
这使我从计划表中获得了3行,但是我想要上面想要的输出。
该怎么做?任何帮助请
答案 0 :(得分:0)
重写您的查询,应该起作用如下。
查询
SELECT
all columns you need
, GROUP_CONCAT(Plan.Plan_Name ORDER BY Plan.planid) AS Planname
FROM
Plan
WHERE
FIND_IN_SET(Plan.plan_id,(
SELECT
User.Plan
FROM
user
WHERE User.userid = 1
)
)
GROUP BY
all columns what are in the select (NOT the GROUP_CONCAT function)
您还可以在FIND_IN_SET
的{{1}}子句上使用ON
。
一个问题是联接将永远不会使用索引。
查询
INNER JOIN
就像我在评论中说的那样,您应该规范化表结构并添加表SELECT
all columns you need
, GROUP_CONCAT(Plan.Plan_Name ORDER BY Plan.planid) AS Planname
FROM
User
INNER JOIN
Plan
ON
FIND_IN_SET(Plan.id, User.Plan)
WHERE
User.id = 1
GROUP BY
all columns what are in the select (NOT the GROUP_CONCAT function)
,这将保持表User_Plan
和User
之间的关系。