具有多个条件的Mysql查询

时间:2014-04-09 10:06:05

标签: mysql

简单地说:我有一张表

columns : col1 col2 col3 col4 col5 col6 col7
datas   : val1  2   toto   t   f    f    f
          val1  2   toto   t   t    f    f
          val1  2   toto   f   t    f    t
          val2  3   tata   t   f    f    t
          val5  4   tutu   f   t    f    f

我想要一个查询给我这个:val1 2 toto t t f t(条件是col2 = 2)=>当在最后4列中的任何一列中找到t时,一行中的前3行为t

有没有办法在一个查询中实现这个目标?

2 个答案:

答案 0 :(得分:0)

Truefalse位于内部10。因此简单

SELECT
  col1, col2, col3, max(col4), 
  max(col5), max(col6), max(col7), 
  sum(col6 + col7) as one_of_them_is_greater_0_meaning_true
from your_table
group by 
  col1, col2, col3

会做的。

编辑:由于你要存储varchars(坏主意),用

替换每个true / false列
CASE WHEN col = 't' THEN 1 ELSE 0 END /*of course replacing column name appropriatelly*/

编辑2:

SELECT
  col1, col2, col3, max(CASE WHEN col4 = 't' THEN 1 ELSE 0 END), 
  max(CASE WHEN col5 = 't' THEN 1 ELSE 0 END), max(CASE WHEN col6 = 't' THEN 1 ELSE 0 END), max(CASE WHEN col7 = 't' THEN 1 ELSE 0 END), 
  sum(CASE WHEN col6 = 't' THEN 1 ELSE 0 END + CASE WHEN col7 = 't' THEN 1 ELSE 0 END) as one_of_them_is_greater_0_meaning_true
from Table1
where col2 = 2
group by 
  col1, col2, col3

1为真,0为假。如果您愿意,可以再次替换它。当然,还要为列使用别名。它只是一个概念证明。

答案 1 :(得分:0)

好的,你可以使用

SELECT field1, field2, field3, 
  MAX(IF(field4 = 't',1,0)) as is_any_field4_true, 
  MAX(IF(field5 = 't',1,0)) as is_any_field5_true, 
  MAX(IF(field6 = 't',1,0)) as is_any_field6_true, 
  MAX(IF(field7 = 't',1,0)) as is_any_field7_true 
GROUP BY field1, field2, field3
相关问题