开发者

Why isn't this simple MySQL statement working?

I am trying to match a user inputted search 开发者_如何学Goterm 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%'
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜