mysql查询是否有可能返回true / false而不是值?

时间:2013-01-15 16:45:27

标签: mysql boolean

我有一张桌子:

custID    orderID    orderComponent
=====================================
1          123        pizza
1          123        wings
1          234        breadsticks
1          239        salad
2          456        pizza
2          890        salad

我有一系列价值观 - 披萨,翅膀,面包棒和沙拉。如果客户至少有一条包含其中每条记录的记录,我需要一种方法来获得真/假值。这是可能的mysql查询,或者我只需为每个用户做select distinct(orderComponent)并使用PHP检查结果?

3 个答案:

答案 0 :(得分:12)

如果您只是想查看客户是否订购了所有商品,那么您可以使用:

select t1.custid,
  case when t2.total is not null 
    then 'true'
    else 'false'
  end OrderedAll
from yourtable t1
left join
(
  select custid, count(distinct orderComponent) Total
  from yourtable
  where orderComponent in ('pizza', 'wings', 'breadsticks', 'salad')
  group by custid
  having count(distinct orderComponent) = 4
) t2
  on t1.custid = t2.custid

请参阅SQL Fiddle with Demo

如果你想扩展它,看看custid是否已经订购了一个订单中的所有商品,那么你可以使用:

select t1.custid,
  t1.orderid,
  case when t2.total is not null 
    then 'true'
    else 'false'
  end OrderedAll
from yourtable t1
left join
(
  select custid, orderid, count(distinct orderComponent) Total
  from yourtable
  where orderComponent in ('pizza', 'wings', 'breadsticks', 'salad')
  group by custid, orderID
  having count(distinct orderComponent) = 4
) t2
  on t1.custid = t2.custid
  and t1.orderId = t2.orderid

请参阅SQL Fiddle with Demo

如果您只想要custid和true / false值,那么您可以在查询中添加distinct

select distinct t1.custid,
  case when t2.total is not null 
    then 'true'
    else 'false'
  end OrderedAll
from yourtable t1
left join
(
  select custid, count(distinct orderComponent) Total
  from yourtable
  where orderComponent in ('pizza', 'wings', 'breadsticks', 'salad')
  group by custid
  having count(distinct orderComponent) = 4
) t2
  on t1.custid = t2.custid

请参阅SQL Fiddle with Demo

或者通过custid和orderid:

select distinct 
  t1.custid,
  t1.orderid,
  case when t2.total is not null 
    then 'true'
    else 'false'
  end OrderedAll
from yourtable t1
left join
(
  select custid, orderid, count(distinct orderComponent) Total
  from yourtable
  where orderComponent in ('pizza', 'wings', 'breadsticks', 'salad')
  group by custid, orderID
  having count(distinct orderComponent) = 4
) t2
  on t1.custid = t2.custid
  and t1.orderId = t2.orderid

请参阅SQL Fiddle with Demo

答案 1 :(得分:2)

select case when 
count(distinct orderComponent) = 4 
then 'true' 
else 'false' 
end as bool
from tbl
where custID=1

答案 2 :(得分:0)

@EmmyS:你可以两种方式做到。 如果要使用MySql检查,请使用:

SELECT @rowcount:=COUNT(*) FROM orderComponent Where (Your Conditions);
IF (@rowcount > 0) THEN
    'True'
ELSE
    'False'
END IF