我有一个SELECT
语句,可以在下表中成功填充我需要的数据。但是我想用if语句过滤掉结果。基本上我想把它放在哪里:
如果Timestamp
和/或msg
有值,则获得结果,否则留空。
<?php foreach ( $result as $query ){ ?>
<tr>
<td><?php echo $query->text1; ?></td>
<td><?php echo $query->text2; ?></td>
<td><?php echo $query->text3; ?></td>
<td><?php if($query->Timestamp!=""){echo date('m/d/y', strtotime($query->Timestamp)); }?></td>
<td><?php echo $query->msg; ?></td>
</tr>
<?php }?>
如何将此if语句写入此代码,以便仅显示生成date
或msg
或两者的行?
根据要求,我已经添加了初始查询,虽然有点复杂,因此我希望避免进一步搞乱它。
$result = $wpdb->get_results(
"SELECT DISTINCT text3,
CASE WHEN text3 LIKE '%S' THEN S_Msg
WHEN text3 LIKE '%N' THEN N_Msg
ELSE E_Msg
END AS msg,
CASE WHEN text3 LIKE '%S' THEN S_Time
WHEN text3 LIKE '%N' THEN N_time
WHEN text3 LIKE '%E' THEN E_time
END AS Timestamp,
value1
FROM table_1 AS a
INNER JOIN table_2 AS b
ON a.Value2 = b.Value3
WHERE value1='$value1'");
我愿意接受有效解决方案的建议:)
我尝试过使用M Khalid Junaid提出的建议
having (msg is not null and msg <> '')
or (Timestamp is not null and Timestamp <> '')
但是这会导致其他查询不再加载的问题,因为我没有使用组,而是在页面上有多个不同的查询,这只是一组更大的查询中的一个。
我担心这个是我的头脑。要在sqlfiddle上复制这个,我需要设置3个数据库表,所以需要一天准备,除非有人有另一个解决方案。我仍然对if语句中的警察持开放态度lol
答案 0 :(得分:1)
要获得满足任何条件的结果,您可以使用以下
select distinct text3,
case when text3 like '%S' then S_Msg when text3 like '%N' then N_Msg else E_Msg end as msg,
case when text3 like '%S' then S_Time when text3 like '%N' then N_time when text3 like '%E' then E_time end as Timestamp,
value1
from table_1 as a
inner join table_2 as b on a.Value2 = b.Value3
where value1='$value1'
having (msg is not null and msg <> '')
or (Timestamp is not null and Timestamp <> '')
不确定您的数据如何在NULL
中保存在数据库中,或者为空,因此我添加了两个过滤器。使用having
子句的目的是对自定义别名应用过滤器
答案 1 :(得分:0)
您可以在检查时间戳或N_msg为空的末尾添加AND语句
$result = $wpdb->get_results(
"SELECT DISTINCT text3,
CASE WHEN text3 like '%S' THEN S_Msg
WHEN text3 like '%N' THEN N_Msg
ELSE E_Msg
END AS msg,
CASE WHEN text3 LIKE '%S' THEN S_Time
WHEN text3 LIKE '%N' THEN N_time
WHEN text3 LIKE '%E' THEN E_time
END AS Timestamp,
value1
FROM table_1 AS a
INNER JOIN table_2 AS b
ON a.Value2 = b.Value3
WHERE value1='$value1'
AND N_msg != '' OR S_time != '' OR N_time != '' OR E_time != ''");
答案 2 :(得分:0)
您可以这样做 - 使用having
子句中的别名
select distinct
text3,
case
when text3 like '%S' then S_Msg
when text3 like '%N' then N_Msg
else E_Msg
end as msg,
case
when text3 like '%S' then S_Time
when text3 like '%N' then N_time
when text3 like '%E' then E_time
end as Timestamp,
value1
from table_1 as a
inner join table_2 as b on a.Value2 = b.Value3
having value1='$value1' and msg is not null and timestamp is not null