基本多样性 - 获取多个数据

时间:2013-08-08 02:39:49

标签: mysql

我有两张桌子,人物和颜色

人们有id,name和colorId(他们喜欢的颜色) 颜色有id和名称

喜欢1种颜色的人很容易获得数据

Select People.name as Pname, Colors.name as Cname 
From People, Colors
Where (People.colorId = Colors.id AND People.id = 1)

但是,我怎么能和一些喜欢2种或更多颜色的人一起做?

3 个答案:

答案 0 :(得分:1)

您希望将group byhaving子句一起使用:

Select People.name as Pname, group_concat(Colors.name) as Cnames
From People join
     Colors
     on People.colorId = Colors.id
group by people.id
having count(*) > 1;

但是,原始查询仅获取id = 1人的颜色。它与产生多少颜色无关。

答案 1 :(得分:0)

Select 
  People.name as Pname, GROUP_CONCAT(Colors.name) as Cname, COUNT(Colors.id) as total_like
From 
  People INNER JOIN Colors ON (People.colorId = Colors.id)
Having 
   total_like > 2

P.S。我不测试

答案 2 :(得分:0)

恕我直言首先您需要更改架构,以便能够正确存储并轻松查询此类数据。您需要将person <-> color关系移动到另一个(数据透视/多对多)表。

建议架构

CREATE TABLE people
    (`id` int, `name` varchar(32));
CREATE TABLE colors
    (`id` int, `name` varchar(32));
CREATE TABLE person_color
    (`person_id` int, `color_id` int);

现在您可以查询您的数据了。获得像

这样的人的颜色
SELECT p.name p_name, c.name c_name 
  FROM person_color pc JOIN people p
    ON pc.person_id = p.id JOIN colors c
    ON pc.color_id = c.id 
 WHERE p.id = 1
 ORDER BY c.id

示例输出:

|  P_NAME | C_NAME |
--------------------
| Person1 |  black |
| Person1 |    red |
| Person1 |   blue |

或喜欢多种颜色的人

SELECT p.name p_name, COUNT(*) how_many_colors
  FROM person_color pc JOIN people p
    ON pc.person_id = p.id
 GROUP BY p.id
HAVING COUNT(*) > 1

示例输出:

|  P_NAME | HOW_MANY_COLORS |
-----------------------------
| Person1 |               3 |

或为喜欢多种颜色的人获取每人的颜色分隔列表

SELECT p.name p_name, GROUP_CONCAT(c.name) colors
  FROM person_color pc JOIN people p
    ON pc.person_id = p.id JOIN colors c
    ON pc.color_id = c.id 
 GROUP BY p.id
HAVING COUNT(*) > 1

示例输出:

|  P_NAME |         COLORS |
----------------------------
| Person1 | black,blue,red |

或者谁更喜欢黑色和蓝色而没有别的

SELECT p.name p_name
  FROM person_color pc JOIN people p
    ON pc.person_id = p.id JOIN colors c
    ON pc.color_id = c.id 
 WHERE c.name IN('black', 'blue')
 GROUP BY p.id
HAVING COUNT(DISTINCT c.id) = 2

示例输出:

|  P_NAME |
-----------
| Person1 |

这是 SQLFiddle 演示