mysql查询关于其他查询的结果集

时间:2018-08-13 08:03:30

标签: php mysql resultset

我的MySQL数据库中有2个自定义表(数据库名称:test)。

我的表格数据如下:

表格:sku

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

表格:猫

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时,结果的类别列中仅得到3。我想像这样:

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

我如何达到预期的效果?

3 个答案:

答案 0 :(得分:2)

添加一个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.

答案 1 :(得分:1)

您可以在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)

答案 2 :(得分:0)

为什么不只在查询末尾添加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%'