tags:

views:

45

answers:

1

I am trying to match a user inputted search term against two tables: posts and galleries. The problem is the union all clause isn't working. Is there something wrong with my code?

$query = mysql_query("

    SELECT * FROM posts WHERE title LIKE '%$searchTerm%'
        OR author LIKE '%$searchTerm%'
        OR location LIKE '%$searchTerm%'
        OR excerpt LIKE '%$searchTerm%'
        OR content LIKE '%$searchTerm%'

        UNION ALL

    SELECT * FROM galleries WHERE title LIKE '%$searchTerm%'

        ");
+1  A: 

When you do UNION ALL on two queries, it requires that you're getting back the same number of columns from both tables, with the same data types, in the same order. Since you're doing SELECT *, this would imply that both posts and galleries have exactly the same number of columns, of the same types, in the same order. I doubt this is the case (but I guess you could get lucky).


Editing to add an example of how you could make this work

You'd need to make the column numbers/types match, which you could do with this sort of method (I'm guessing which columns you need, and just adding "N/A" for columns that I'm assuming don't exist in galleries):

SELECT title, author, location, excerpt, content
FROM posts
WHERE title LIKE '%$searchTerm%'
    OR author LIKE '%$searchTerm%'
    OR location LIKE '%$searchTerm%'
    OR excerpt LIKE '%$searchTerm%'
    OR content LIKE '%$searchTerm%'

UNION ALL

SELECT title, 'N/A', 'N/A', 'N/A', 'N/A'
FROM galleries
WHERE title LIKE '%$searchTerm%'
Chad Birch
Ahh I see, Yes the tables have different named columns and different numbers of columns. So since UNION ALL isn't what I need, what can I use to search both tables, 5 columns from the posts table and 1 from the galleries table?
Clark
@Chad: that depends on the version of mysql; newer versions do a kind of supersetting of the number and types of columns. See http://dev.mysql.com/doc/refman/5.5/en/union.html
wallyk
@Clark You can still do it with `UNION ALL`, you'll just have to define the columns explicitly. I don't know much about your table structures, but I'll edit my answer with an example of how it could work.
Chad Birch
Thank you Chad this works wonderfully!
Clark