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