如果...语句满足两个条件,则mysql选择true

时间:2012-05-11 10:04:23

标签: mysql

我有一个带有布尔值的表,我想知道一组id是否同时具有这两个值。

这个sql选择我要测试的产品组:

SELECT 
  cp.ItemID,
  cp.IsUnitsOfMeasure
from grouped_products gp
LEFT JOIN products p ON p.product_id = gp.product_id
LEFT JOIN c_products cp ON cp.ItemID = p.product_id
WHERE gp.group_id=123

我想知道该组的cp.IsUnitsOfMeasure是否包含1和0。

2 个答案:

答案 0 :(得分:1)

试试这个:

SELECT 
    cp.ItemID,
    SUM(cp.IsUnitsOfMeasure) AS sum,
    COUNT(cp.IsUnitsOfMeasure) AS count,
    from grouped_products gp
LEFT JOIN products p ON p.product_id = gp.product_id
LEFT JOIN c_products cp ON cp.ItemID = p.product_id
WHERE gp.group_id=123
  • 如果sum等于count,则所有行都为1
  • 如果sum等于0,则所有行都为0
  • 在所有其他情况下:组中有1和0

答案 1 :(得分:0)

SELECT   gp.group_id,
         SUM(cp.IsUnitsOfMeasure=0) AND SUM(cp.IsUnitsOfMeasure=1) AS ContainsBoth,
FROM     grouped_products AS gp
  LEFT JOIN products      AS  p USING (product_id)
  LEFT JOIN c_products    AS cp ON cp.ItemID = p.product_id
GROUP BY gp.group_id

ContainsBothTRUEFALSE表示每个相应的群组是否包含两者 c_product IsUnitsOfMeasure=0 另一个=1