获取组中的条目列表。 MySQL的

时间:2012-08-31 16:31:54

标签: mysql sql stored-procedures

我有一个只生成Project ID的表。 project_table,其中包含project_id和其他列。

我有另一个表格project_members,其中有两列project_idFOREIGN KEYproject_tableuser_id列。

我想知道一组用户(以逗号分隔值传递)是否属于同一个project_id

例如 - project_members表具有以下条目

project_id user_id
         1       1
         1       2
         2       3
         2       4
         2       1

当我通过id's 1,2时,我想知道这些用户中有哪些project_id。条件是该项目中只有ids 1 and 2

因此上述数据的输入和输出应为 -

input output
1,2        1
1,2,3   NONE
1,3,4      2
1,2,4   NONE.

怎么可能?

1 个答案:

答案 0 :(得分:3)

SELECT   project_id
FROM     project_members
WHERE    user_id IN (1,3,4)
GROUP BY project_id
HAVING   COUNT(*) = 3

sqlfiddle上查看。

请注意,这假设(project_id, user_id)中没有重复的project_members条记录。如果存在重复项,则需要使用价格较高的COUNT(DISTINCT user_id)代替COUNT(*)


如果您必须在存储过程中执行此操作,则可以使用MySQL的FIND_IN_SET()函数代替IN运算符,并计算总计CHAR_LENGTH()中的计数减去删除了所有逗号的输入字符串:

CREATE PROCEDURE get_projects(IN members TEXT)
SELECT   project_id
FROM     project_members
WHERE    FIND_IN_SET(user_id, members)
GROUP BY project_id
HAVING   COUNT(*) = 1 + CHAR_LENGTH(members)-CHAR_LENGTH(REPLACE(members,',',''));

请注意,这假定members包含以逗号分隔的不同 user_id值,而不包含其他填充或多余内容。


要查找包含指定确切成员的项目,可以改为:

SELECT   project_id
FROM     project_members
GROUP BY project_id
HAVING   COUNT(*) = 3
     AND NOT SUM(user_id NOT IN (1,3,4))

程序版本将是:

CREATE PROCEDURE get_projects(IN members TEXT)
SELECT   project_id
FROM     project_members
GROUP BY project_id
HAVING   COUNT(*) = 1 + CHAR_LENGTH(members)-CHAR_LENGTH(REPLACE(members,',',''))
     AND NOT SUM(FIND_IN_SET(user_id, members)=0);