SubQuery with EXISTS and NOT EXISTS in PHP
SELECT with SubQuery Syntax :
SELECT columns FROM table1 WHERE column = (SELECT columns FROM table2 WHERE condition);
In "personal" table, there are 6 columns named id, name, percentage, age, gender, city.
In "personal" table, column name "id" is PRIMARY KEY and column name "city" is FOREIGN KEY.
In "courses" table, there are 2 columns named course_id and course_name.
In "courses" table, column name "course_id" is PRIMARY KEY.
In "city" table, there are 2 columns named cid and cityname.
In "city" table, column name "cid" is PRIMARY KEY.
If we want to select records from "personal" table who belong to Delhi from "city" table using SubQuery then we can use below shown sql query :
SELECT name FROM personal WHERE city = (SELECT cid FROM city WHERE cityname = "Delhi");
If we want to select records from "personal" table who belong to Delhi and Agra from "city" table using SubQuery then we can use below shown sql query :
SELECT name FROM personal WHERE city IN (SELECT cid FROM city WHERE cityname IN ("Delhi","Agra"));
SELECT with EXISTS Syntax :
SELECT columns FROM table1 WHERE EXISTS(SELECT columns FROM table2 WHERE condition);
NOTE : If any Single Record Exists in Child command then Parent command show results.
SELECT with NOT EXISTS Syntax :
SELECT columns FROM table1 WHERE NOT EXISTS(SELECT columns FROM table2 WHERE condition);
NOTE : If not any Single Record Exists in Child command then Parent command show results.
If we want to apply EXISTS in above query then we can use below shown sql query :
SELECT name FROM personal WHERE city EXISTS (SELECT cid FROM city WHERE cityname IN ("Delhi"));
If we want to apply NOT EXISTS in above query then we can use below shown sql query :
SELECT name FROM personal WHERE city NOT EXISTS (SELECT cid FROM city WHERE cityname IN ("Delhi"));
Comments
Post a Comment