简体   繁体   中英

Why isn't this simple MySQL statement working?

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%'

        ");

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%'

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