Mysql Union如何检查行是否存在? [英] How to do Mysql Union with check if row exists?

查看:129
本文介绍了Mysql Union如何检查行是否存在?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,这有点复杂,因为我的表没有被引用或合并或彼此匹配,所以我不能使用JOIN的表.我正在建立一个搜索表单,该表单将简单地匹配多个表中的搜索关键字.

OK this is bit complicated because my tables are not referenced or combined or to be matched with each other so I cant use JOIN's. I am building a search form that would simply match search keyword in multiple tables.

我遇到的问题是,我必须根据结果来自哪个表来生成新闻项链接,但是我找不到钩子. MySql联合工作完美,除了我不能检查数据是来自表a还是表b.

The issue I have is that I have to generate news item link depending from which table the result came but I cant find a hook. MySql union works perfect except that I cant check if data is from table a or table b.

here is short version 
SELECT  i.title,i.category FROM table_a  WHERE REGEXP 'news'
UNION 
SELECT i.title,i.category FROM table_b WHERE REGEXP 'news'

现在,我的表A有36行,表B有34行,另外一个区别是表A具有要检查的行名extra_field并基于该链接我的链接.

now , my table A has 36 rows and table B has 34 , one more difference is that table A has row name extra_field which I wanted to check and based on that switch my link.

查询后的php切换可能类似于

php switch after query could be something like

foreach($rows as $row) :
if($row->extra_field):
$link = 'index.php?".$row->category.$row->title".html'
else:
$link = 'index.php?".$row->title".html'
endif;
endforeach;

那么有没有一种方法可以检查我的UNION sql是否存在?我知道如何检查行是否存在,但是如何在UNION中进行检查?

So is there a way to check in my UNION sql if that row exists? I know how to check if row exists but how to do that in UNION?

请帮助.谢谢!

推荐答案

以您的简短版本为例,您可以在查询中添加一个额外的列:

Using your short version as an example, you could add an extra column to the query:

SELECT  i.title,i.category,'a' as source FROM table_a  WHERE REGEXP 'news'
UNION 
SELECT i.title,i.category, 'b' as source FROM table_b WHERE REGEXP 'news'

然后,您可以在代码中检查源"列.

Then in your code you could check the 'source' column.

这篇关于Mysql Union如何检查行是否存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆