如何选择在另一个字段中具有特定值的字段的所有值?

时间:2017-03-01 18:48:46

标签: mysql

我有一个表格,其中字段'id_px'可以有一些重复值,因为它在字段'id_category'中有不同的值,我想要检索'id_px'上具有我通过的确切值的所有值。例如:

SELECT id_px FROM my_table WHERE id_category = 1 **AND** id_category = 32;

我找到了一种方法来检索我想要的结果:

SELECT id_px
FROM my_table
GROUP BY id_px
HAVING SUM(id_category NOT IN (1,32)) = 0
AND SUM(id_category = 1) = 1
AND SUM(id_category = 32) = 1

但是我想使用它来使用HAVING子句,因为我必须使用一些UNION子句。

希望你能提前帮助我。

1 个答案:

答案 0 :(得分:-1)

我建议采取一些方法:

3- 3月:(工作并标记为答案)

SELECT tbl.id_px FROM
  (SELECT id_px ,
    SUM(id_category NOT IN (1,32)) as b ,
    SUM(id_category = 1) as t1 , SUM(id_category = 32) as t2
  FROM my_table
  GROUP BY id_px) as tbl
WHERE tbl.b = 0 AND tbl.t1 = 1 AND tbl.t2 = 1

4-重新构建查询-2:

4.1-重建的第一步:( 效率低下

SELECT tbl.id_px FROM
  (SELECT id_px , CONCAT('-,' , GROUP_CONCAT(id_category),',') as gr
   FROM my_table
   GROUP BY id_px
  ) as tbl
  WHERE
      INSTR( tbl.gr , ',1,'  )>0
  AND INSTR( tbl.gr , ',32,' )>0
  AND LENGTH(tbl.gr)-LENGTH(REPLACE(REPLACE(tbl.gr,',1,' ,''), ',32,' ,'')) = LENGTH(CONCAT(',1,' , ',32,' ))

WHERE中的最后一个条件正在替换tbl.gr中的1和32,并且如果减少的长度等于1和32个字符串,则比较减少的LENGTH,只有1和32所以重写查询到这一个:

4.2-新的可能工作查询:(简化

SELECT tbl.id_px FROM
  (SELECT id_px , GROUP_CONCAT(id_category) as gr
   FROM my_table
   GROUP BY id_px
  ) as tbl
  WHERE
      tbl.gr = '1,32' or tbl.gr = '32,1'

没有任何样本数据似乎这些都没问题,但是他们没有很好的答案,而问题是将id_category限制为具有两个值而没有其他id_category。

注意:这两个查询选择id_pxid_category 1,32个,也许还有许多其他id_category,因此这个问题不能接受

2-按id_px

选择join
SELECT a.id_px
FROM my_table as a
LEFT JOIN my_table as b
ON a.id_px = b.id_px
WHERE a.id_category = 1 AND b.id_category = 32
GROUP BY a.id_px

1-使用group by并搜索id_px

SELECT tbl.id_px FROM
  (SELECT id_px , CONCAT('-,' , GROUP_CONCAT(id_category),',') as gr
   FROM my_table
   GROUP BY id_px
  ) as tbl
  WHERE
      INSTR( tbl.gr , ',1,'  )>0
  AND INSTR( tbl.gr , ',32,' )>0