MySQL - 遍历行

时间:2013-04-02 17:35:50

标签: mysql sql database loops rows

我有以下代码

select count(*)
from (select Annotations.user_id
from Annotations, Users
where Users.gender =  'Female'
and Users.user_id = Annotations.user_id
and image_id = 1
group by Annotations.user_id
having sum(case when stem = 'taxi' then 1 else 0 end) > 0 and
       sum(case when stem = 'zebra crossing' then 1 else 0 end) > 0
) Annotations

它显示了为图像1提供干“出租车”和“斑马线”的女性数量。

示例数据

 user id, image id, stem
 1           1      image
 1           1      taxi
 1           1      zebra crossing
 2           1      person
 2           1      zebra crossing
 2           1      taxi
 3           1      person
 3           1      zebra crossing

预期结果(或类似)

stem1,  stem2,            count
taxi ,  zebra crossing      2
person, zebra crossing      2

然而,由于有超过2000个词干,我无法全部指定它们。

我如何使用image_id = 1和gender = female循环遍历词干行而不是指定词干串?

谢谢

3 个答案:

答案 0 :(得分:1)

更新:据我所知,您想要选择2个词干的所有组合,并计算有多少个用户拥有词干组合的计数。这是我的解决方案:

SELECT stem1, stem2, count(*) as count FROM
(
    SELECT a.user_id,a.image_id,a.stem as stem1,b.stem as stem2
    FROM Annotations a JOIN Annotations b
    ON a.user_id=b.user_id && b.image_id=a.image_id && a.stem!=b.stem
    JOIN Users ON Users.user_id = a.user_id
    WHERE Users.gender = "Female"
) as stems GROUP BY stem1, stem2 having count > 1 WHERE image_id=1;

这里需要注意的是,对于每个茎的组合,它将返回2行。 (第二次出现的词干的顺序相反)。

答案 1 :(得分:1)

根据我的理解,您需要获取具有2 or more stems 的女性用户

更新:您似乎需要显示其他用户也使用过干的用户,我已更新相同的查询

 SELECT
    distinct a.user_id,
    group_concat(DISTINCT a.stem ORDER BY a.stem)
 FROM
    Annotations a 
    JOIN Users u ON ( a.user_id = u.user_id AND u.gender =  'Female' )
    JOIN 
        (
            SELECT 
                b.user_id,
                b.stem
            FROM
                Annotations b
        ) AS b ON ( a.user_id <> b.user_id AND b.stem = a.stem )
 WHERE
    a.image_id = 1
GROUP BY
  a.user_id

答案 2 :(得分:0)

这是我尝试解决您的问题:

SELECT COUNT(*) AS Count, a1.stem AS Stem1, a2.Stem AS Stem2 
FROM Annotations AS a1
INNER JOIN Annotations AS a2 ON a1.user_id = a2.user_id AND a1.image_id = a2.image_id
                          AND a1.stem < a2.stem 
WHERE a1.image_id = 1
GROUP BY a1.stem, a2.Stem
HAVING COUNT(*) > 1; 

我没有包含image_id逻辑。

请在此处查看我的SQL小提琴:http://sqlfiddle.com/#!2/4ee69/33

根据以下数据(从您的数据中复制),我会在其下方公布结果。

CREATE TABLE Annotations
    (`user_id` int, `image_id` int, `stem` varchar(14))
;

INSERT INTO Annotations
    (`user_id`, `image_id`, `stem`)
VALUES
    (1, 1, 'image'),
    (1, 1, 'taxi'),
    (1, 1, 'zebra crossing'),
    (2, 1, 'person'),
    (2, 1, 'zebra crossing'),
    (2, 1, 'taxi'),
    (3, 1, 'person'),
    (3, 1, 'zebra crossing')
;

  COUNT STEM1   STEM2
    2   person  zebra crossing
    2   taxi    zebra crossing