max max -4 years ago 58
MySQL Question

How to search for string in two mysql tables without fulltext indexes

I have this query to searching for some string in two tables(download, news)
and return column called title from that record,
but there is something wrong with the code. Its just showing result from second table in the code, and if I change tables place in the code again I'm getting result from second table!

$sql="SELECT download.title,news.title FROM download,news WHERE download.title LIKE '%$search%' OR news.title LIKE '%$search%' OR news.text LIKE '%$search_text%' ";


and printing results

while ($row = mysql_fetch_assoc($result)) {
echo $row['title'] ."<br/>";
}

Answer Source

Use:

SELECT d.title
  FROM DOWNLOAD d
 WHERE d.title LIKE '%$search%' 
UNION 
SELECT n.title
  FROM NEWS n
 WHERE n.title LIKE '%$search%' 
    OR n.text LIKE '%$search%' 

The query you posted produces a cartesian product because there's no JOIN criteria in the WHERE clause. This query will return a list of distinct title values based on the records in either table. If there were no chance of the query returning duplicates, I'd have used UNION ALL instead.

How to find out which table result are from ?


Without knowing more about the tables, the easiest way would be to define a computed/derived column with static values:

SELECT d.title,
       'DOWNLOAD' AS type
  FROM DOWNLOAD d
 WHERE d.title LIKE '%$search%' 
UNION 
SELECT n.title,
       'NEWS' AS type
  FROM NEWS n
 WHERE n.title LIKE '%$search%' 
    OR n.text LIKE '%$search%' 

The type column indicates which table the record came from. However, this raises a potential issue -

There is the possibility that there is an identical title in both tables - the resultset would look like this:

TITLE      TYPE
----------------------
abc_title  DOWNLOAD
abc_title  NEWS
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download