MYSQL realizes the global search of the platform

Foreword:

The project requires that the search box on the home page can input keywords to directly search for information in the information list and question list on the platform. What everyone thinks is to return the list directly to the table like title name!

But now there is such a situation, the information list and the question list are two separate database tables, it must be operated by union, but some fields are different, as follows:

wejoy_new

 wejoy_questions

You can see that the field names of the category id are different, and it will be embarrassing at this time, fill in the empty fields? NO! I don't want to do this!

solution 

 sql:

select title, content, cid, null as qid from wejoy_news where title like '%测试%'
union
select title, content, null as cid, qid from wejoy_questions where title like '%测试%';

When querying, we can use null to complete the result. The result is as follows:

 This will solve the problem!

What? In this way, the returned list has to be judged from which table is used for front-end judgment?

Just add a field when outputting!

select title, content, cid, null as qid, 'wejoy_news' as source from wejoy_news where title like '%测试%'
union
select title, content, null as cid, qid, 'wejoy_questions' as source from wejoy_questions where title like '%测试%';

 thinkphp5 query code

Db::table('wejoy_news')
->field('id,title,content,cid as cid,null as qid,\'news\' as source')
->where('title','like','%关键词%')
->union(function($query){
    $query->table('wejoy_questions')
    ->field('id,title,content,null as cid,qid as qid,\'questions\' as source')
    ->where('title','like','%关键词%');
})
->select();
$articles = new Articles();
$questions = new Questions();

$articles->field('id,title,content,cid as cid,null as qid,\'articles\' as source')
->where('title','like','%关键词%')
->union(function($query){
    $query->table('questions')
    ->field('id,title,content,null as cid,qid as qid,\'questions\' as source')
    ->where('title','like','%关键词%');
})
->select();

Guess you like

Origin blog.csdn.net/weixin_47723549/article/details/130198302