Question

I m creating a search using php , there i need to search companies from company name and company category .

*company_content tb*

title categories _id

*company_category tb*

title (category name) id parent_id (categories id on on content table)

here's my query

    $query=mysql_query("SELECT  b.title FROM  sltdb_cddir_content a, sltdb_cddir_categories b
WHERE  b.title like '%".$searchg."%' AND b.parent_id=81 UNION
SELECT  a.title  FROM  sltdb_cddir_content a, sltdb_cddir_categories b
WHERE a.categories_id=b.id  AND  a.title like '%".$searchg."%' AND b.parent_id=81");

is this type of union valid ? please advice

UPDATE 01

   $query=mysql_query("SELECT  b.title
FROM sltdb_cddir_categories b
WHERE  b.title like '%".$searchg."%' AND b.parent_id = 81
UNION
SELECT  a.title
FROM  sltdb_cddir_content a join
      sltdb_cddir_categories b
      on a.categories_id = b.id
WHERE a.title like '%".$searchg."%' AND b.parent_id = 81");
$json=array();
while($display=mysql_fetch_array($query)){
    $json[]=array(
        'value'=> $display["title"],
        'label'=>$display["title"]
    );
}




echo json_encode($json);
Was it helpful?

Solution

This is your query:

SELECT  b.title
FROM  sltdb_cddir_content a, sltdb_cddir_categories b
WHERE  b.title like '%".$searchg."%' AND b.parent_id=81
UNION
SELECT  a.title
FROM  sltdb_cddir_content a, sltdb_cddir_categories b
WHERE a.categories_id=b.id  AND  a.title like '%".$searchg."%' AND b.parent_id=81;

In the first subquery, the join to a is unimportant. The values are never used. This seems to be an equivalent query:

SELECT  b.title
FROM sltdb_cddir_categories b
WHERE  b.title like '%".$searchg."%' AND b.parent_id = 81
UNION
SELECT  a.title
FROM  sltdb_cddir_content a join
      sltdb_cddir_categories b
      on a.categories_id = b.id
WHERE a.title like '%".$searchg."%' AND b.parent_id = 81;

If the purpose is to get all titles from the two tables where the corresponding parent_id is 81 and the title matches the pattern, then this query looks reasonable.

OTHER TIPS

I'd go for a LEFT JOIN query

SELECT a.title, b.title 
FROM  sltdb_cddir_content a 
LEFT JOIN sltdb_cddir_categories b
ON a.categories_id=b.id
WHERE  (b.title like '%".$searchg."%' OR a.title like '%".$searchg."%')
AND b.parent_id = 81
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top