Возможно ли, чтобы запрос mysql возвращал true/false вместо значений?
У меня есть таблица:
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 для проверки результатов?
Ответы
Ответ 1
Если вы просто хотите узнать, заказал ли клиент все предметы, вы можете использовать:
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
Ответ 2
select case when
count(distinct orderComponent) = 4
then 'true'
else 'false'
end as bool
from tbl
where custID=1
Ответ 3
Здесь один подход. Этот подход не требует встроенного представления (производная таблица) и может быть эффективным, если вы хотите включить флаги для нескольких условий:
EDIT:
Это возвращает custID
, у которого есть строка для всех четырех элементов:
SELECT t.custID
, MAX(IF(t.orderComponent='breadsticks',1,0))
+ MAX(IF(t.orderComponent='pizza',1,0))
+ MAX(IF(t.orderComponent='salad',1,0))
+ MAX(IF(t.orderComponent='wings',1,0)) AS has_all_four
FROM mytable t
GROUP BY t.custID
HAVING has_all_four = 4
ОРИГИНАЛЬНЫЙ ОТВЕТ:
(Это проверено для заказа клиента, в котором было все четыре элемента, а не только "custID".)
SELECT t.custID
, t.orderID
, MAX(IF(t.orderComponent='breadsticks',1,0))
+ MAX(IF(t.orderComponent='pizza',1,0))
+ MAX(IF(t.orderComponent='salad',1,0))
+ MAX(IF(t.orderComponent='wings',1,0)) AS has_all_four
-- , MAX(IF(t.orderComponent='breadsticks',1,0)) AS has_breadsticks
-- , MAX(IF(t.orderComponent='pizza',1,0)) AS has_pizza
-- , MAX(IF(t.orderComponent='salad',1,0)) AS has_salad
-- , MAX(IF(t.orderComponent='wings',1,0)) AS has_wings
FROM mytable t
GROUP BY t.custID, t.orderID
HAVING has_all_four = 4
Это получит "заказы", в которых есть все четыре элемента. Если вы хотите вернуть только значения для custID, используйте вышеприведенный запрос в виде встроенного представления (оберните его в другой запрос).
SELECT s.custID
FROM (
SELECT t.custID
, t.orderID
, MAX(IF(t.orderComponent='breadsticks',1,0))
+ MAX(IF(t.orderComponent='pizza',1,0))
+ MAX(IF(t.orderComponent='salad',1,0))
+ MAX(IF(t.orderComponent='wings',1,0)) AS has_all_four
FROM mytable t
GROUP BY t.custID, t.orderID
HAVING has_all_four = 4
) s
GROUP BY s.custID
Ответ 4
@EmmyS: вы можете сделать это в обоих направлениях.
Если вы хотите проверить использование MySql:
SELECT @rowcount:=COUNT(*) FROM orderComponent Where (Your Conditions);
IF (@rowcount > 0) THEN
'True'
ELSE
'False'
END IF