如何解决PHP-MySQL-销毁/忽略表字段如果它不包含任何值/为空
美好的一天!我试图将一个表加入另一个表。是否可以破坏或忽略表字段,例如blotter_entry
如果它不包含任何值或如果它是null
?通过查看下面的屏幕截图,您可以看到我有三个带有blotter_entry
的表。那么,用户是否属于res_id
或tbl_complainant as tc
或tbl_respondent as te
,则实际上取决于用户或tbl_victim as tv
。
在屏幕快照中,查询发现在blotter_entry
中找到了tbl_complainant
,如何从blotter_entry
中忽略两个tbl_respondent and tbl_victim
?
之所以这样问,是因为无论何时我循环此SQL查询并执行echo $row['blotter_entry']
以便将其显示在网站中,因为如果检测到res_id
并找到了tbl_respondent and tbl_victim
,它将不会显示网页中的任何内容。例如,res_id
是数字3,他是受访者/受害者。每当我在网站上输出echo $row['blotter_entry']
时。它不会显示任何内容。
任何帮助将不胜感激。谢谢!
Screenshot after running this SQL Query
SELECT tr.res_id,tc.res_id,tc.blotter_entry,te.res_id,te.blotter_entry,tv.res_id,tv.blotter_entry,tb.blotter_id,tb.blotter_type,tb.blotter_reporteddate,tb.blotter_reportedtime,tb.blotter_incidentdate,tb.blotter_incidenttime,tb.blotter_status,tc.complainant_name,te.respondent_name,tv.victim_name
FROM tbl_resident tr
LEFT
JOIN tbl_complainant tc
on tr.res_id = tc.res_id
LEFT
JOIN tbl_respondent te
on tr.res_id = te.res_id
LEFT
JOIN tbl_victim tv
on tr.res_id = tv.res_id
LEFT
JOIN tbl_blotter tb
on tc.blotter_entry = tb.blotter_entry
OR te.blotter_entry = tb.blotter_entry
OR tv.blotter_entry = tb.blotter_entry
WHERE tr.res_id = 1;
解决方法
您可以使用coalesce()
来使用第一个非null
值。
select
tr.res_id,coalesce(tc.blotter_entry,te.blotter_entry,tv.blotter_entry) as blotter_entry
tb.blotter_id,tb.blotter_type,tb.blotter_reporteddate,tb.blotter_reportedtime,tb.blotter_incidentdate,tb.blotter_incidenttime,tb.blotter_status,tc.complainant_name,te.respondent_name,tv.victim_name
from tbl_resident tr
left join tbl_complainant tc on tr.res_id = tc.res_id
left join tbl_respondent te on tr.res_id = te.res_id
left join tbl_victim tv on tr.res_id = tv.res_id
left join tbl_blotter tb on tb.blotter_entry in (tc.blotter_entry,tv.blotter_entry)
where tr.res_id = 1;
注意:
-
res_id
在select
子句中也模棱两可;它在不同的表中多次出现。由于这是您用于join
和过滤的列,因此足以为from
子句中的第一个表带来值 -
我简化了最后一个表的连接条件,以使用
in
而不是重复的or
条件
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。