设置查询的常用方法
SELECT * from ____
WHERE (Column1>0) and ____就像在问“哪些记录的column1值>0且column2 .....”?
然而,现在我想以相反的方式来做,
对于此记录,值大于0的列是什么?
给定指定的记录ID,如果列值满足条件,如何编写返回列名的查询?有一些非整数列,可以忽略不计。
编辑:我的表包含许多只接受0或1值的列。
SELECT id from ____
WHERE Views>5000 and Q1=1 and Q3=1然后进行随机化,然后显示和结果哪些列= 1。
“结果: ID:_____。Views:____。Q1,Q3,Q6,Q14,Q38,Q45,Q56存在。(=1)”
现在从答案上看,我似乎必须逐列检查,而不是使用自动检查所有列的函数,因此我认为无论我使用SQL还是使用PHP进行后处理,方法都必须相同。我只是希望一些函数可以做到这一点,而不是编写循环。
发布于 2016-07-16 16:00:38
您可以根据CASE、WHEN或if为每一列构建一个字符串,如果值大于0,则应对这些列进行验证。
例如:
CREATE TABLE test_tbl(
id INT NOT NULL AUTO_INCREMENT,
col1 INT,
col2 INT,
col3 INT,
PRIMARY KEY ( id )
);
insert into test_tbl (col1,col2,col3)
values
(0,0,0),
(8,0,0),
(8,null,8),
(8,8,8);
select
*,
TRIM(TRAILING ',' FROM
concat(
if(col1 > 0,'col1,',''),
case when col2 > 0 then 'col2,' else '' end,
if(col3 > 0,'col3,','')
)
) as bigger_than_0
from test_tbl
where (col1>0 or col2>0 or col3>0);提供:
id col1 col2 col3 bigger_than_0
2 8 0 0 col1
3 8 null 8 col1,col3
4 8 8 8 col1,col2,col3发布于 2016-07-16 15:26:03
对于MySQL,我可以想到两种可能性,分别是CASE和IF语句,例如
SELECT
id,
case
when a.column1 > 0 then 'column1'
else null
end AS col1,
case
when a.column2 > 0 then 'column2'
else null
end AS col2
FROM table_a a;
SELECT
id,
IF(column1 > 0, 'column 1', 'null') as col1,
IF(column2 > 0, 'column 2', 'null') as col2
FROM table_a a;发布于 2016-07-16 16:01:33
这是你想知道的:
create table TT(col1 int,col2 int,col3 int);
insert into TT values(1,0,1);
insert into TT values(4,0,5);
insert into TT values(1,0,3);
insert into TT values(1,0,0);
select distinct
'col1' as 'Column contains values >1'
from
TT
where
col1 > 0
union
select distinct
'col2' as 'Column contains values >1'
from
TT
where
col2 > 0
union
select distinct
'col3' as 'Column contains values >1'
from
TT
where
col3 > 0;结果:
+---------------------------+
| Column contains values >1 |
+---------------------------+
| col1 |
| col3 |
+---------------------------+因为col1和col3的值都大于0,所以您可以根据自己的喜好自定义查询
https://stackoverflow.com/questions/38408365
复制相似问题