WHERE x = y works, but WHERE x != y doesn't

Questions about the MySQL, PostgreSQL, and most other databases, as well as using it with PHP can be asked here.

Moderator: General Moderators

Post Reply
rhecker
Forum Contributor
Posts: 178
Joined: Fri Jul 11, 2008 5:49 pm

WHERE x = y works, but WHERE x != y doesn't

Post by rhecker »

I have two queries, each based on two tables. The first returns all rows where a field in one table matches the other, and that query works fine, but oddly, the query which should return the opposite, all rows where there is no match, doesn't work. Any thoughts?

Code: Select all

mysql_query("select title, page_content.page_id FROM page_content, menu WHERE page_content.page_id != menu.page_id GROUP BY page_id")
rhecker
Forum Contributor
Posts: 178
Joined: Fri Jul 11, 2008 5:49 pm

Re: WHERE x = y works, but WHERE x != y doesn't

Post by rhecker »

The key to the solution turned out to be "WHERE NOT EXISTS" as follows:

Code: Select all

SELECT title, page_id FROM page_content WHERE NOT EXISTS(SELECT page_id FROM menu WHERE menu.page_id = page_content.page_id) GROUP BY page_id
Post Reply