mysql对其他查询结果集的查询

jpfvwuh4  于 2021-06-23  发布在  Mysql
关注(0)|答案(3)|浏览(376)

我的mysql数据库中有两个自定义表(db name:test)。
我的表格数据如下:
表:sku

entity_id   sku
1           24-MB01
2           24-MB03
3           24-UB02
4           24-UB01

表:cat

id  entity_id   category
1   1           3
2   2           3
3   1           5
4   2           7
5   4           4
6   3           50
7   3           20
8   3           21
9   4           3

我使用以下查询来获取有关sku值的逗号分隔类别:

SELECT sku.entity_id, sku.sku, GROUP_CONCAT(cat.category SEPARATOR ",") as category 
FROM sku, cat 
WHERE cat.entity_id = sku.entity_id 
GROUP by sku.entity_id

下面是使用上述查询找到的结果集:

entity_id   sku         category
1           24-MB01     3,5
2           24-MB03     7,3
3           24-UB02     21,50,20
4           24-UB01     4,3

现在,我想使用这个结果集来查找特定类别的记录(假设类别id为3)。当我在查询中使用find\ in\ set时,在结果的category列中只得到3个。我想让它像:

entity_id   sku         category
1           24-MB01     3,5
2           24-MB03     7,3
4           24-UB01     4,3

怎样才能达到预期的效果?

6xfqseft

6xfqseft1#

为什么不直接加上 HAVING category LIKE '%3%' 在你的询问结束时?
所以,完整的查询如下:

SELECT sku.entity_id, 
    sku.sku, 
    GROUP_CONCAT(cat.category SEPARATOR ",") as category 
FROM sku, cat 
WHERE cat.entity_id = sku.entity_id 
GROUP by sku.entity_id
HAVING category LIKE '%3%'
pxy2qtax

pxy2qtax2#

你可以使用 HAVING 带的子句 FIND_IN_SET :

SELECT sku.entity_id, 
    sku.sku, 
    GROUP_CONCAT(cat.category SEPARATOR ",") as category 
FROM sku, cat 
WHERE cat.entity_id = sku.entity_id 
GROUP by sku.entity_id
HAVING FIND_IN_SET(3, category)
mfpqipee

mfpqipee3#

添加 HAVING 条款:

SELECT sku.entity_id, 
    sku.sku, 
    GROUP_CONCAT(cat.category SEPARATOR ",") as category 
FROM sku, cat 
WHERE cat.entity_id = sku.entity_id 
GROUP by sku.entity_id
HAVING SUM(cat.category = 3) > 0;

(顺便说一下,这在mysql中使用了true=1,false=0。在其他dbms中 HAVING SUM(CASE WHEN cat.category = 3 THEN 1 ELSE 0 END) > 0. )

相关问题