dqh19413 2018-08-13 08:03
浏览 110

Mysql查询其他查询的结果集

I have 2 custom tables in my MySQL database (DB name: test).

The data of my tables is given below:

Table: sku

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

Table: 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

I am using the following query to get the comma separated categories with respect to sku values:

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

Below is the result set found using the above query:

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

Now, I want to use this result set to find records for a particular category (say the category id is 3). When I used FIND_IN_SET in my query, I am getting only 3 in the category column in the result. I want to get it like:

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

How can I achieve the desired result?

  • 写回答

3条回答 默认 最新

  • douran7929 2018-08-13 08:15
    关注

    Add a HAVING clause:

    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;
    

    (This makes use of true = 1, false = 0 in MySQL, by the way. In other DBMS that would be HAVING SUM(CASE WHEN cat.category = 3 THEN 1 ELSE 0 END) > 0.)

    评论

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。