The Codex of Business Writing Software for Real-World Solutions 2.pptx
Mysql joins example table and query process
1. Mysql Subquries Example and Query Process
Mysql Subquery
Explanation :
Subquery or Inner query or Nested query is a query in a query.mysql subquery is usually added
in the WHERE Clause of the mysql statement. Most of the time, a subquery is used when you
know how to search for a value using a SELECT statement, but do not know the exact value in
the database.
Subqueries are an alternate way of returning data from multiple tables.
Subqueries can be used with the following SQL statements along with the comparision
operators like
Syntax:
SELECT column_list FROM table-name
[WHERE Clause]
[GROUP BY clause]
[HAVING clause]
[ORDER BY clause];
Real Time Query Car ShowRoom Example
DROP TABLE IF EXISTS `cars`;
CREATE TABLE `cars` (
`id` int(10) unsigned NOT NULL auto_increment,
`name` varchar(450) NOT NULL,
2. `cost` double NOT NULL,
PRIMARY KEY (`id`)
) ;
INSERT INTO `cars` (`id`,`name`,`cost`) VALUES
(1,'Audi',52642),
(2,'Mercedes',57127),
(3,'Skoda',9000),
(4,'Volvo',29000),
(5,'Bentley',350000),
(6,'Citroen',21000),
(7,'Hummer',41400),
(8,'Volkswagen ',21600);
DROP TABLE IF EXISTS `cus_table`;
CREATE TABLE `cus_table` (
`customer_id` int(10) unsigned NOT NULL auto_increment,
`name` varchar(450) NOT NULL,
PRIMARY KEY USING BTREE (`customer_id`)
) ;
INSERT INTO `cus_table` (`customer_id`,`name`) VALUES
(1,'Paul Novak'),
(2,'Terry Neils'),
(3,'Jack Fonda'),
3. (4,'Tom Willis');
DROP TABLE IF EXISTS `reservations`;
CREATE TABLE `reservations` (
`id` int(10) unsigned NOT NULL auto_increment,
`customer_id` varchar(45) NOT NULL,
`Day` datetime NOT NULL,
PRIMARY KEY (`id`)
) ;
INSERT INTO `reservations` (`id`,`customer_id`,`Day`) VALUES
(1,'1','2017-11-22 00:00:00'),
(2,'2','2017-11-22 00:00:00'),
(3,'3','2017-11-22 00:00:00'),
(4,'4','2017-11-22 00:00:00');
Scalar subqueries
SELECT name FROM cus_table WHERE
customer_id=(SELECT customer_id FROM reservations WHERE id=4);
OUTPUT :
4. Table subqueries
SELECT name FROM cus_table WHERE customer_id IN
(SELECT DISTINCT customer_id FROM reservations);
SELECT DISTINCT name FROM cus_table JOIN reservations
ON cus_table.customer_id=reservations.customer_id;
OUTPUT :
Correlated subqueries
SELECT name FROM cars WHERE cost <
(SELECT AVG(cost) FROM cars);
SELECT name FROM cus_table WHERE NOT EXISTS
(SELECT * FROM reservations WHERE
cus_table.customer_id=reservations.customer_id);
OUTPUT :