Dhaval Simariya
Dhaval Simariya

Reputation: 67

SQL query with AND OR operator

I have this sql query

SELECT entries.*, categories.name as name_cat, areas.name as name_area, sub_categories.name as name_sub
FROM entries, areas, sub_categories, categories
WHERE sub_categories.id= entries.id_sub
  AND **areas.id = entries.area**
  AND categories.id = entries.id_cat
ORDER BY entries.id DESC

It works good but i do have some BLANK fields in entries.area .. which is not coming in result..

I try few changes in query but some give me result while some give less nothing gives me proper Answer

Upvotes: 2

Views: 63

Answers (1)

spencer7593
spencer7593

Reputation: 108370

It's 2015 already. It's past time to ditch the old-school comma syntax for the join operator, and use the JOIN keyword instead. With the JOIN keyword, we can move the predicates (conditions) from the WHERE clause to an ON clause.

Using the JOIN keyword, we can specify an "outer join" by including additional keyword(s).

For example, including the keyword LEFT (before JOIN) specifies that the query should return rows from the table on the "left" side even when no matching row exists in the table on the right side.

 SELECT entries.*
      , categories.name      AS name_cat
      , areas.name           AS name_area
      , sub_categories.name  AS name_sub
   FROM entries
   LEFT
   JOIN areas
     ON areas.id = entries.area
   LEFT
   JOIN sub_categories
     ON sub_categories.id= entries.id_sub
   LEFT
   JOIN categories
     ON categories.id = entries.id_cat
  WHERE 1=1
  ORDER BY entries.id DESC

The line WHERE 1=1 can be omitted... I included it just to show where a WHERE clause would go, if we needed one.

Upvotes: 4

Related Questions