简体   繁体   English

Mysql Union如何检查行是否存在?

[英]How to do Mysql Union with check if row exists?

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. 好的,这有点复杂,因为我的表没有被引用或合并或彼此匹配,所以我不能使用JOIN的表。 I am building a search form that would simply match search keyword in multiple tables. 我正在建立一个搜索表单,该表单将简单地匹配多个表中的搜索关键字。

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. MySql联合工作完美,除了我不能检查数据是来自表a还是表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'

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. 现在,我的表A有36行,表B有34行,另一个区别是表A具有要检查的行名extra_field并基于该链接我的链接。

php switch after query could be something like 查询后的php切换可能类似于

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;

So is there a way to check in my UNION sql if that row exists? 那么,有没有一种方法可以检查我的UNION SQL是否存在? I know how to check if row exists but how to do that in UNION? 我知道如何检查行是否存在,但如何在UNION中进行检查?

Please help. 请帮忙。 Thank you! 谢谢!

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. 然后,您可以在代码中检查“源”列。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM