2

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

人们有 id、name 和 colorId(他们喜欢的颜色) 颜色有 id 和 name

喜欢1色的人容易获取数据

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

但是,对于喜欢 2 种或更多颜色的人,我该怎么办?

4

3 回答 3

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. 它与产生多少颜色无关。

于 2013-08-08T02:44:00.983 回答
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

PS我不测试

于 2013-08-08T02:48:49.213 回答
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 |
--------------------
| 人1 | 黑色 |
| 人1 | 红色 |
| 人1 | 蓝色 |

或者喜欢不止一种颜色的人

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 |
-----------------------------------------
| 人1 | 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 | 颜色 |
----------------------------
| 人1 | 黑、蓝、红 |

或者谁喜欢黑色和蓝色而不是别的

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 |
------------
| 人1 |

等等

这是SQLFiddle演示

于 2013-08-08T02:54:07.447 回答