在SQL查询/子查询中选择匹配和不匹配的结果

时间:2015-09-28 15:17:20

标签: mysql sql

我试图找到与短片颜色最相似的项目相对于他们拥有的颜色总数。我可以很容易地首先选择匹配计数,然后对于每个匹配的项目分别选择总计数然后除以,但我更愿意在单个语句中执行此操作,如果可能的话,最小化最终将是数百,如果不是成千上万的疑问。

开始查询:

SELECT clothes,
        COUNT(clothes.id) AS matches
 FROM clothes
    AND clothes.item!='shorts' 
    AND clothes.colors IN (
        SELECT clothes.colors 
        FROM clothes 
        WHERE item='shorts' 
        DESC LIMIT 5000
    ) 

 GROUP BY item ORDER BY matches DESC

表设置:

id  | item    | colors
=========================
1   | shorts  | red 
2   | shorts  | blue 
3   | shorts  | green
4   | pants   | red 
5   | pants   | blue
6   | pants   | white
7   | shirts  | red 
8   | shirts  | blue 
9   | shirts  | gray 
10  | shirts  | orange 
11  | shirts  | purple 
12  | shirts  | black 
13  | shirts  | white 
14  | shirts  | tan 
15  | shirts  | fuscia 

目标输出

Item   | Matches | Total | Ratio
==================================
pants  | 2       | 3     | 2/3
shirts | 2       | 9     | 2/9

有关如何在单个查询语句中执行此操作的任何想法?

1 个答案:

答案 0 :(得分:0)

总计全部,使用计数。要仅匹配匹配的,请使用CASE和SUM:

SELECT clothes.Item, SUM(
        CASE WHEN clothes.
                colors IN (
                    SELECT clothes.
                        colors
                    FROM clothes
                    WHERE item = 
                        'shorts' DESC 
                        LIMIT 5000
                    ) THEN 1 ELSE 0 END) 
    Matches, COUNT(clothes.
        id) AS matches, CAST(SUM
        (CASE WHEN clothes.
                    colors IN (
                        SELECT clothes
                            .colors
                        FROM clothes
                        WHERE item = 
                            'shorts' 
                            DESC LIMIT 
                            5000
                        ) THEN 1 ELSE 0 
                END) AS VARCHAR) + 
    '/' + CAST(COUNT(clothes.
            id) AS VARCHAR) AS 
    Ratio
FROM clothes clothes.item != 
    'shorts'