简体   繁体   中英

Query same field from two different tables MYSQL

I've been having an issue trying to query 3 tables and 2 with the same field. Using php and mysql

example

TableA TableB TableC

keyword in the query would be a search term.

SELECT 
   title 
FROM TableA as A 
LEFT JOIN TableC as C 
   ON TableA.id=TableC.id 
WHERE 1 
   AND TableC.private='0' 
   AND ( 
        title LIKE '".$keyword."%' 
     OR title LIKE '%".$keyword."%' 
     OR title LIKE '%".$keyword."' 
     OR title = '".$keyword."' 
   )

The problem I'm having is I ALSO need to simultaneously search TableB for title and do a match based on the same keyword. How do I incorporate TableB title field into the query?

So if there is say TableA with title=America and TableB with title=American it will display both results from both tables since it would match the LIKE query.

Then with PHP show the result. If TableA or TableB matches show that result(s). And loop through the array etc.

It has to be in a query because I'm using it for a search parameter.

TIA

Do a union:

SELECT title FROM TableA as A LEFT JOIN TableC as C ON TableA.id=TableC.id WHERE 1 AND TABLEC.private='0' AND ( title LIKE '".$keyword."%' OR title LIKE '%".$keyword."%' 
             OR title LIKE '%".$keyword."' OR title = '".$keyword."' )
UNION
SELECT title FROM TableB as B LEFT JOIN TableC as C ON TableB.id=TableC.id WHERE 1 AND TABLEC.private='0' AND ( title LIKE '".$keyword."%' OR title LIKE '%".$keyword."%' 
             OR title LIKE '%".$keyword."' OR title = '".$keyword."' )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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