MySQL Query Optimization - Avoiding Subqueries - mysql

I need to update some rows in my table, for simplicity called "three".
I select the columns to update with this query:
SELECT one.id
FROM one
JOIN `two` ON ( one.id = two.page )
JOIN `three` ON ( one.id = three.item )
WHERE two.level = 1
AND two.item = (SELECT item FROM two WHERE page = 5 AND level = 1 )
AND three.position > (SELECT position FROM three WHERE item = 5 )
ORDER BY three.position
Now I call an update query with id's I get.
Is there any chance to eliminate the subqueries?
Edit (after Melanie's comment):
Table "one":
|id|text|
Table "two":
|id|item|page|level|
Table "three":
|item|position|
So when I run the query
SELECT item FROM two WHERE page = 5 AND level = 1
It will return f.ex 1 and the final WHERE clause will be:
two.item = 1 AND two.level = 1
Which is not the same as:
two.level = 1 and two.page = 5
I have the table one - some text with some one.id. I need to update all items from table three which has higher position than my item (f.ex. id = 5) have. But those items should also have the same two.item in table two, where two.page = one.id and level = 1
I am sorry for a poor description.

You should be able to replace those subqueries by joins:
SELECT one.id
FROM one
JOIN `two2` ON (two2.page = 5 AND two2.level = 1)
JOIN `two` ON ( one.id = two.page AND two.item = two2.item )
JOIN `three2` ON ( three.item = 5)
JOIN `three` ON ( one.id = three.item AND three.position > three2.position)
WHERE two.level = 1
ORDER BY three.position

#TheVedge is interesting solution but does not produce the same result as your query
I suggest to avoid duplicate the same table also with a view so a little correction
Another correction is three2.item=5
I suggest to use in subquery limit 0,1 so never return more then one element
SELECT one.id
FROM one
JOIN `two` AS TWO2 ON (two2.page = 5 AND two2.level = 1)
JOIN `two` ON ( one.id = two.page AND two.item = two2.item )
JOIN `three` AS THREE2 ON ( three2.item = 5)
JOIN `three` ON ( one.id = three.item AND three.position > three2.position)
WHERE two.level = 1
ORDER BY three.position
Remember that you are not doing the same thing with this query.
Try this
CREATE TABLE `one` (
`id` INT(10) NULL DEFAULT NULL,
`text` VARCHAR(50) NULL DEFAULT NULL
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB;
_
CREATE TABLE `three` (
`item` INT(10) NULL DEFAULT NULL,
`position` INT(10) NULL DEFAULT NULL
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB;
_
CREATE TABLE `two` (
`id` INT(10) NULL DEFAULT NULL,
`item` INT(10) NULL DEFAULT NULL,
`page` INT(10) NULL DEFAULT NULL,
`level` INT(10) NULL DEFAULT NULL
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB;
_
INSERT INTO `two` (`id`, `item`, `page`, `level`) VALUES (1, 1, 5, 1);
INSERT INTO `two` (`id`, `item`, `page`, `level`) VALUES (3, 3, 5, 1);
INSERT INTO `two` (`id`, `item`, `page`, `level`) VALUES (4, 4, 5, 1);
INSERT INTO `two` (`id`, `item`, `page`, `level`) VALUES (5, 5, 5, 1);
INSERT INTO `two` (`id`, `item`, `page`, `level`) VALUES (6, 6, 5, 1);
INSERT INTO `two` (`id`, `item`, `page`, `level`) VALUES (7, 7, 5, 1);
INSERT INTO `two` (`id`, `item`, `page`, `level`) VALUES (8, 8, 5, 1);
INSERT INTO `two` (`id`, `item`, `page`, `level`) VALUES (9, 9, 5, 1);
INSERT INTO `two` (`id`, `item`, `page`, `level`) VALUES (2, 2, 5, 1);
INSERT INTO `two` (`id`, `item`, `page`, `level`) VALUES (10, 2, 1, 1);
INSERT INTO `two` (`id`, `item`, `page`, `level`) VALUES (11, 1, 1, 1);
INSERT INTO `two` (`id`, `item`, `page`, `level`) VALUES (13, 3, 1, 1);
INSERT INTO `two` (`id`, `item`, `page`, `level`) VALUES (14, 4, 1, 1);
INSERT INTO `two` (`id`, `item`, `page`, `level`) VALUES (15, 5, 1, 1);
INSERT INTO `two` (`id`, `item`, `page`, `level`) VALUES (16, 6, 1, 1);
INSERT INTO `two` (`id`, `item`, `page`, `level`) VALUES (17, 7, 1, 1);
INSERT INTO `two` (`id`, `item`, `page`, `level`) VALUES (18, 8, 1, 1);
INSERT INTO `two` (`id`, `item`, `page`, `level`) VALUES (19, 9, 1, 1);
INSERT INTO `two` (`id`, `item`, `page`, `level`) VALUES (20, 2, 2, 1);
INSERT INTO `two` (`id`, `item`, `page`, `level`) VALUES (21, 1, 2, 1);
INSERT INTO `two` (`id`, `item`, `page`, `level`) VALUES (23, 3, 2, 1);
INSERT INTO `two` (`id`, `item`, `page`, `level`) VALUES (24, 4, 2, 1);
INSERT INTO `two` (`id`, `item`, `page`, `level`) VALUES (25, 5, 2, 1);
INSERT INTO `two` (`id`, `item`, `page`, `level`) VALUES (26, 6, 2, 1);
INSERT INTO `two` (`id`, `item`, `page`, `level`) VALUES (27, 7, 2, 1);
INSERT INTO `two` (`id`, `item`, `page`, `level`) VALUES (28, 8, 2, 1);
INSERT INTO `two` (`id`, `item`, `page`, `level`) VALUES (29, 9, 2, 1);
INSERT INTO `two` (`id`, `item`, `page`, `level`) VALUES (30, 2, 3, 1);
INSERT INTO `two` (`id`, `item`, `page`, `level`) VALUES (31, 1, 3, 1);
INSERT INTO `two` (`id`, `item`, `page`, `level`) VALUES (33, 3, 3, 1);
INSERT INTO `two` (`id`, `item`, `page`, `level`) VALUES (34, 4, 3, 1);
INSERT INTO `two` (`id`, `item`, `page`, `level`) VALUES (35, 5, 3, 1);
INSERT INTO `two` (`id`, `item`, `page`, `level`) VALUES (36, 6, 3, 1);
INSERT INTO `two` (`id`, `item`, `page`, `level`) VALUES (37, 7, 3, 1);
INSERT INTO `two` (`id`, `item`, `page`, `level`) VALUES (38, 8, 3, 1);
INSERT INTO `two` (`id`, `item`, `page`, `level`) VALUES (39, 9, 3, 1);
INSERT INTO `two` (`id`, `item`, `page`, `level`) VALUES (40, 2, 4, 1);
INSERT INTO `two` (`id`, `item`, `page`, `level`) VALUES (41, 1, 4, 1);
INSERT INTO `two` (`id`, `item`, `page`, `level`) VALUES (42, 3, 4, 1);
INSERT INTO `two` (`id`, `item`, `page`, `level`) VALUES (43, 4, 4, 1);
INSERT INTO `two` (`id`, `item`, `page`, `level`) VALUES (44, 5, 4, 1);
INSERT INTO `two` (`id`, `item`, `page`, `level`) VALUES (45, 6, 4, 1);
INSERT INTO `two` (`id`, `item`, `page`, `level`) VALUES (46, 7, 4, 1);
INSERT INTO `two` (`id`, `item`, `page`, `level`) VALUES (47, 8, 4, 1);
INSERT INTO `two` (`id`, `item`, `page`, `level`) VALUES (48, 9, 4, 1);
-
INSERT INTO `three` (`item`, `position`) VALUES (1, 1);
INSERT INTO `three` (`item`, `position`) VALUES (2, 1);
INSERT INTO `three` (`item`, `position`) VALUES (3, 1);
INSERT INTO `three` (`item`, `position`) VALUES (4, 1);
INSERT INTO `three` (`item`, `position`) VALUES (5, 0);
INSERT INTO `three` (`item`, `position`) VALUES (6, 1);
INSERT INTO `three` (`item`, `position`) VALUES (7, 1);
INSERT INTO `three` (`item`, `position`) VALUES (8, 1);
INSERT INTO `three` (`item`, `position`) VALUES (9, 1);
INSERT INTO `three` (`item`, `position`) VALUES (10, 1);
INSERT INTO `three` (`item`, `position`) VALUES (11, 1);
INSERT INTO `three` (`item`, `position`) VALUES (12, 1);
_
INSERT INTO `one` (`id`, `text`) VALUES (1, 'A');
INSERT INTO `one` (`id`, `text`) VALUES (2, 'B');
INSERT INTO `one` (`id`, `text`) VALUES (3, 'C');
INSERT INTO `one` (`id`, `text`) VALUES (4, 'D');
INSERT INTO `one` (`id`, `text`) VALUES (5, 'E');
INSERT INTO `one` (`id`, `text`) VALUES (6, 'F');
INSERT INTO `one` (`id`, `text`) VALUES (7, 'G');
_
SELECT
one.id, one.text
,two.id,two.item,two.page,two.level
,three.item,three.position
FROM one
JOIN `two` ON ( one.id = two.page )
JOIN `three` ON ( one.id = three.item )
WHERE two.level = 1
AND two.item = (SELECT item FROM two WHERE page = 5 AND level = 1 limit 0,1 )
AND three.position > (SELECT position FROM three WHERE item = 5 limit 0,1 )
ORDER BY three.position
SELECT
one.id, one.text
,two.id,two.item,two.page,two.level
,three.item,three.position
FROM one
JOIN `two` AS TWO2 ON (two2.page = 5 AND two2.level = 1)
JOIN `two` ON ( one.id = two.page AND two.item = two2.item )
JOIN `three` AS THREE2 ON ( three2.item = 5)
JOIN `three` ON ( one.id = three.item AND three.position > three2.position)
WHERE two.level = 1
ORDER BY three.position
With original query you made a select of specific element in TheVedge solution you are joining more data
So result depend on what you select
Another useful analysis is http://dev.mysql.com/doc/refman/5.0/en/show-profile.html and Explain
Show Profile show that at the first run
your original query does
Status Duration
starting 0.000039
checking query cache for query 0.000144
Opening tables 0.000032
System lock 0.000007
Table lock 0.000061
init 0.000054
optimizing 0.000314
statistics 0.000021
preparing 0.000051
Creating tmp table 0.000084
executing 0.000004
Copying to tmp table 0.000063
optimizing 0.000008
statistics 0.000019
preparing 0.000009
executing 0.000004
Sending data 0.000054
optimizing 0.000008
statistics 0.000007
preparing 0.000009
executing 0.000003
Sending data 0.000126
Sorting result 0.000030
Sending data 0.000025
end 0.000004
removing tmp table 0.000011
end 0.000005
query end 0.000004
freeing items 0.000101
storing result in query cache 0.000008
logging slow query 0.000003
cleaning up 0.000006
Proposed query does
Status Duration
starting 0.000036
checking query cache for query 0.000122
Opening tables 0.000030
System lock 0.000008
Table lock 0.000064
init 0.000046
optimizing 0.000028
statistics 0.000026
preparing 0.000072
Creating tmp table 0.000086
executing 0.000005
Copying to tmp table 0.001081
Sorting result 0.000040
Sending data 0.000056
end 0.000005
removing tmp table 0.000010
end 0.000005
query end 0.000004
freeing items 0.000108
storing result in query cache 0.000007
logging slow query 0.000003
cleaning up 0.000005
So when you have full data you can try to evalute better the response of both query

Related

Unable to Add More Than One Field in Table in MySQL

I'm trying to add a table in a MySQL database. The database is called "stocks". The odd thing I'm encountering is that while I can create the table, I can't add any fields to it other than the primary key.
Code is below. Please note that I can create the "person" table and all of its fields and populate all fields without a problem. The "quotes" table and "person_quotes" table can be created, too, but I cannot populate them with any fields other than the primary key. Anyone have any idea what's going on?
/* delete tables if they exist already - ensuring a clean db */
DROP TABLE IF EXISTS stocks.person CASCADE;
DROP TABLE IF EXISTS stocks.quotes CASCADE;
DROP TABLE IF EXISTS stocks.person_quotes CASCADE;
/** creates a table to store a list of persons */
CREATE TABLE stocks.person
(
person_ID INT PRIMARY KEY NOT NULL,
first_name VARCHAR(256) NOT NULL,
last_name VARCHAR(256) NOT NULL,
birth_date DATETIME NOT NULL
);
/* creates a table to store a list of quotes */
CREATE TABLE stocks.quotes
(
quotes_ID INT PRIMARY KEY NOT NULL,
symbol VARCHAR(256) NOT NULL,
quote_time DATETIME NOT NULL,
price DECIMAL NOT NULL
);
/** A list of people and their quotes */
CREATE TABLE stocks.person_quotes
(
person_quote_ID INT PRIMARY KEY NOT NULL,
person_id INT NOT NULL,
quotes_id INT NOT NULL,
FOREIGN KEY (person_id) REFERENCES person (person_ID),
FOREIGN KEY (quotes_id) REFERENCES quotes (quotes_ID)
);
/** add some sample data */
INSERT INTO quotes (quotes_ID,symbol,quote_time,price) VALUES (1, 'GOOG', '2018-09-21 00:00:01', 85);
INSERT INTO quotes (quotes_ID,symbol,quote_time,price) VALUES (2, 'GOOG', '2018-09-21 00:00:59', 95);
INSERT INTO quotes (quotes_ID,symbol,quote_time,price) VALUES (3, 'GOOG', '2018-09-21 01:00:01', 105);
INSERT INTO quotes (quotes_ID,symbol,quote_time,price) VALUES (4, 'GOOG', '2018-09-21 02:00:01', 115);
INSERT INTO quotes (quotes_ID,symbol,quote_time,price) VALUES (5, 'GOOG', '2018-09-21 03:00:01', 125);
INSERT INTO quotes (quotes_ID,symbol,quote_time,price) VALUES (6, 'GOOG', '2018-09-22 00:00:01', 135);
INSERT INTO quotes (quotes_ID,symbol,quote_time,price) VALUES (7, 'GOOG', '2018-09-22 01:00:01', 145);
INSERT INTO quotes (quotes_ID,symbol,quote_time,price) VALUES (8, 'GOOG', '2018-09-22 02:00:01', 155);
INSERT INTO quotes (quotes_ID,symbol,quote_time,price) VALUES (9, 'GOOG', '2018-09-22 03:00:01', 165);
INSERT INTO quotes (quotes_ID,symbol,quote_time,price) VALUES (10, 'GOOG', '2018-09-23 00:00:01', 175);
INSERT INTO quotes (quotes_ID,symbol,quote_time,price) VALUES (11, 'GOOG', '2018-09-24 00:00:01', 185);
INSERT INTO quotes (quotes_ID,symbol,quote_time,price) VALUES (12, 'GOOG', '2018-09-25 00:00:01', 195);
INSERT INTO quotes (quotes_ID,symbol,quote_time,price) VALUES (13, 'GOOG', '2018-09-26 00:00:01', 205);
INSERT INTO quotes (quotes_ID,symbol,quote_time,price) VALUES (14, 'GOOG', '2018-09-27 00:00:01', 215);
INSERT INTO quotes (quotes_ID,symbol,quote_time,price) VALUES (15, 'GOOG', '2018-09-28 00:00:01', 225);
INSERT INTO quotes (quotes_ID,symbol,quote_time,price) VALUES (16, 'GOOG', '2018-09-29 00:00:01', 235);
INSERT INTO quotes (quotes_ID,symbol,quote_time,price) VALUES (17, 'GOOG', '2018-09-30 00:00:01', 245);
INSERT INTO quotes (quotes_ID,symbol,quote_time,price) VALUES (18, 'GOOG', '2018-09-30 00:00:01', 255);
INSERT INTO quotes (quotes_ID,symbol,quote_time,price) VALUES (19, 'GOOG', '2018-10-01 00:00:01', 265);
INSERT INTO quotes (quotes_ID,symbol,quote_time,price) VALUES (20, 'GOOG', '2018-10-02 00:00:01', 275);
INSERT INTO person (person_ID,first_name,last_name,birth_date) VALUES (1, 'Drew', 'Hope', '1999/10/10');
INSERT INTO person (person_ID,first_name,last_name,birth_date) VALUES (2, 'Lang', 'Heckman', '1959/11/11');
INSERT INTO person (person_ID,first_name,last_name,birth_date) VALUES (3, 'Lucy', 'Jones', '2010/1/1');
INSERT INTO person (person_ID,first_name,last_name,birth_date) VALUES (4, 'Stew', 'Hammer', '1990/3/28');
INSERT INTO person (person_ID,first_name,last_name,birth_date) VALUES (5, 'Dan', 'Lane', '1986/4/18');
INSERT INTO person (person_ID,first_name,last_name,birth_date) VALUES (6, 'James', 'Marrese', '1915/10/18');
INSERT INTO person_quotes (person_quotes_ID, person_id, quotes_id) VALUES (1, 1, 2);
INSERT INTO person_quotes (person_quotes_ID, person_id, quotes_id) VALUES (2, 1, 1);
INSERT INTO person_quotes (person_quotes_ID, person_id, quotes_id) VALUES (3, 2, 1);
INSERT INTO person_quotes (person_quotes_ID, person_id, quotes_id) VALUES (4, 3, 1);
INSERT INTO person_quotes (person_quotes_ID, person_id, quotes_id) VALUES (5, 3, 3);
INSERT INTO person_quotes (person_quotes_ID, person_id, quotes_id) VALUES (6, 3, 4);
INSERT INTO person_quotes (person_quotes_ID, person_id, quotes_id) VALUES (7, 4, 7);

Gap Locks or not

CREATE TABLE `z` (
`a` int(11) NOT NULL,
`b` int(11) DEFAULT NULL,
PRIMARY KEY (`a`),
KEY `b` (`b`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO `test`.`z` (`a`, `b`) VALUES (1, 1);
INSERT INTO `test`.`z` (`a`, `b`) VALUES (3, 1);
INSERT INTO `test`.`z` (`a`, `b`) VALUES (5, 3);
INSERT INTO `test`.`z` (`a`, `b`) VALUES (7, 6);
INSERT INTO `test`.`z` (`a`, `b`) VALUES (10, 8);
INSERT INTO `test`.`z` (`a`, `b`) VALUES (20, 30);
INSERT INTO `test`.`z` (`a`, `b`) VALUES (50, 60);
INSERT INTO `test`.`z` (`a`, `b`) VALUES (45, 90);
INSERT INTO `test`.`z` (`a`, `b`) VALUES (2, 99);
transaction_isolation = REPEATABLE-READ
tx_isolation = REPEATABLE-READ
SESSION 1
begin;
select * from z where b = 60 for update;
SESSION 2
begin;
insert into z select 4, 90; /* why this can't be insert? */
ERROR 1205 (HY000): Lock wait timeout exceeded; try restarting transaction
insert into z select 46, 90; /* But this can be insert? */
Query OK, 1 row affected (0.00 sec)
Records: 1 Duplicates: 0 Warnings: 0
As the above step:
one can be insert, but the other can't be. they're all the same value - 90.
Yes, this is a gap lock.
The two inserts are not actually trying to insert the same value, because secondary indexes also store a copy of the primary key at the end (that is how an index lookup finds the original row if more columns are referenced than are in the index).
In the index b, the rows in question would be sorted like this.
b a
60, 50
90, 4
90, 45
90, 46
From this illustration, you can see that (4,90) belongs in the gap immediately after (60,50), but (46,90) is not in that gap.

Condition based selecting from group_concat in Mysql query

Here is my table and sample data.
CREATE TABLE `articles`
(
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`title` varchar(100) NOT NULL,
PRIMARY KEY (`id`)
);
CREATE TABLE `tags`
(
`id` int(11) NOT NULL,
`name` varchar(100) NOT NULL,
PRIMARY KEY (`id`)
);
CREATE TABLE `article_tags`
(
`article_id` int(11) NOT NULL,
`tag_id` int(11) NOT NULL
);
INSERT INTO `tags` (`id`, `name`) VALUES
(1, 'Wap Stories'),
(2, 'App Stories');
INSERT INTO `articles` (`id`, `title`) VALUES
(1, 'USA'),
(2, 'England'),
(3, 'Germany'),
(4, 'India'),
(5, 'France'),
(6, 'Dubai'),
(7, 'Poland'),
(8, 'Japan'),
(9, 'China'),
(10, 'Australia');
INSERT INTO `article_tags` (`article_id`, `tag_id`) VALUES
(1, 1),
(1, 2),
(4, 1),
(5, 1),
(2, 2),
(2, 1),
(6, 2),
(7, 2),
(8, 1),
(9, 1),
(3, 2),
(9, 2),
(10, 2);
How can I get the below output I have tried using group_concat function. It gives all the results. But my requirement is I need to groupconcat values as
a. Combination of 1,2 can be there, only 1 can be there but 2 alone cannot be there.
b. Combination of 2,1 can be there, only 2 can be there but 1 alone cannot be there
Below is the output I need
id, title, groupconcat
--------------------------
1, USA, 1,2
2, England, 1,2
4, India, 1
5, France, 1
8, Japan, 1
9, China, 1,2
SqlFiddle Link
The query which I am using is
select id, title, group_concat(tag_id order by tag_id) as 'groupconcat' from articles a
left join article_tags att on a.id = att.article_id
where att.tag_id in (1,2)
group by article_id order by id
You can try like this
SELECT id, title, GROUP_CONCAT(tag_id ORDER BY tag_id) AS 'groupconcat'
FROM articles a
LEFT join article_tags att on a.id = att.article_id
WHERE att.tag_id in (1,2)
GROUP BY article_id
HAVING SUBSTRING_INDEX(groupconcat,',',1) !='2'
ORDER BY id

Needing assistance with counting the most different books

Which customer(s) ordered the most different books? Display the customer id and include ties. This is not talking about the quantity of books ordered. For example, suppose my only orders are Customer 1 ordered 400 copies of book_id 34 Customer 2 ordered 2 copies of book_id 62 and 3 copies of book_id 29 Customer 1 ordered a larger quantity of books but customer 2 ordered more different books. The query should - in this case- return customer 2:
Here is my attempted solution. Not sure how to solve this one:
SELECT cust_id
FROM a_bkorders.customers
WHERE cust_id IN
(
SELECT cust_id
FROM a_bkorders.order_headers
Join a_bkorders.order_details using (order_id)
GROUP BY cust_id
HAVING count(book_id) <=
(
SELECT MAX(numBooks)
FROM (
SELECT cust_id
, count(book_id) AS numBooks
Join a_bkorders.order_details using (order_id)
FROM a_bkorders.order_headers
GROUP BY cust_id
) t
)
)ORDER BY cust_id;
Here are the tables:
-- create customers
create table a_bkorders.customers (
cust_id integer not null
, cust_name_last varchar(20) not null
, cust_name_first varchar(20) null
, cust_state char(2) not null
, cust_postal_code char(10) not null
, cust_acct_opened date not null
, constraint bk_cust_pk primary key (cust_id)
, constraint bk_cust_id_range check (cust_id > 1000)
, constraint bk_cust_acct_opened_ck check (cust_acct_opened >= '1975-01-01' )
)engine = INNODB;
-- create order_headers
create table a_bkorders.order_headers (
order_id integer not null
, order_date date not null
, cust_id integer not null
, constraint bk_orders_pk primary key (order_id)
, constraint bk_orders_cust_fk foreign key(cust_id)
references a_bkorders.customers(cust_id)
, constraint bk_order_id_range check (order_id > 100)
, constraint bk_order_date_ck check (order_date >= '2000-01-01')
)engine = INNODB;
-- create order_details
create table a_bkorders.order_details (
order_id integer not null
, order_line integer not null
, book_id integer not null
, quantity integer not null
, order_price numeric(6,2) not null
, constraint bk_orderline_pk primary key (order_id, order_line)
, constraint bk_orderline_order_fk foreign key (order_id)
references a_bkorders.order_headers(order_id) on delete cascade
, constraint bk_orderline_book_fk foreign key (book_id )
references a_bkinfo.books(book_id)
, constraint bk_quantity_ck check (quantity > 0)
, constraint bk_ordprice_ck check (order_price >= 0)
)engine = INNODB;
Here are the inserts:
-- customers
insert into a_bkorders.customers values (208950, 'Adams', 'Samuel', 'MA', '02106', '1996-04-15' );
insert into a_bkorders.customers values (200368, 'Blake', 'William', 'CA', '95959', '1997-07-15' );
insert into a_bkorders.customers values (258595, 'Jobs', 'Peter', 'MA', '02575', '1997-01-09' );
insert into a_bkorders.customers values (263119, 'Jones', null, 'IL', '62979', '1997-03-02' );
insert into a_bkorders.customers values (224038, 'Austin', 'Pat', 'CA', '95900', '1997-08-02' );
insert into a_bkorders.customers values (255919, 'Milton', 'John', 'NJ', '08235', '2011-05-31' );
insert into a_bkorders.customers values (211483, 'Carroll', 'Lewis', 'CA', '94203', '1998-08-08' );
insert into a_bkorders.customers values (221297, 'Dodgson', 'Charles', 'MI', '49327', '2001-05-06' );
insert into a_bkorders.customers values (261502, 'Hawthorne', 'Nathaniel', 'MA', '02297', '2001-10-12' );
insert into a_bkorders.customers values (212921, 'Books on Tap', NULL, 'CA', '94112', '2002-01-06' );
insert into a_bkorders.customers values (260368, 'Muller', 'Jonathan', 'IL', '62885', '2005-12-15' );
insert into a_bkorders.customers values (259969, 'Carlsen', 'Benny', 'NJ', '08505', '2011-07-12' );
insert into a_bkorders.customers values (239427, 'Marksa', 'Anna', 'NJ', '08495', '2011-02-28' );
insert into a_bkorders.customers values (296598, 'Collins', 'Douglas', 'MO', '65836', '2005-04-25' );
insert into a_bkorders.customers values (276381, 'Collins', 'Douglas', 'OH', '22451', '2005-02-08' );
insert into a_bkorders.customers values (234138, 'Keats', 'John', 'IL', '61500', '2006-04-30' );
insert into a_bkorders.customers values (267780, 'Shelly', 'Mary', 'CA', '94100', '2010-10-02' );
insert into a_bkorders.customers values (290298, 'Swift', 'Jonathan', 'MI', '49201', '2010-10-12' );
insert into a_bkorders.customers values (226656, 'Randall', 'Randell', 'NJ', '08251', '2011-08-08' );
insert into a_bkorders.customers values (222477, 'Rossetti', 'Christina', 'MI', '49742', '2011-07-11' );
insert into a_bkorders.customers values (227105, 'Kafka', 'Franz', 'MA', '02297', '2010-12-31' );
insert into a_bkorders.customers values (202958, 'Denver', null, 'IL', '60405', '2011-01-15' );
insert into a_bkorders.customers values (218709, 'Bonnard', 'Paul', 'MA', '02558', '2005-11-15' );
insert into a_bkorders.customers values (217796, 'Anders', null, 'IL', '62505', '2011-03-30' );
insert into a_bkorders.customers values (272787, 'Carlson', 'Ben', 'IL', '62505', '2011-05-05' );
insert into a_bkorders.customers values (234709, 'Brahms', 'Johnnie', 'MA', '02558', '2012-01-15' );
insert into a_bkorders.customers values (217002, 'Grieg', 'Edvard', 'IL', '62329', '2012-02-29' );
insert into a_bkorders.customers values (272611, 'Jarrett', 'Keith', 'IL', '62329', '2011-11-11' );
insert into a_bkorders.customers values (299099, 'Sam', 'Dave', 'CA', '94141', '2011-01-01' );
insert into a_bkorders.customers values (259906, 'Capybara', 'Wile E.', 'CA', '94132', '2012-01-05' );
insert into a_bkorders.customers values (259907, 'Hedge', 'Mr.', 'CA', '94132', '2011-09-05' );
insert into a_bkorders.customers values (282716, 'Biederbecke','Dwight', 'PA', '18106', '2013-01-01' );
insert into a_bkorders.customers values (287261, 'Biederbecke','Bix', 'PA', '18106', '2012-01-01' );
insert into a_bkorders.customers values (226275, 'Dalrymple','Jack', 'SD', '57216', '2013-01-01' );
insert into a_bkorders.customers values (228175, 'Cardin','Benjamin', 'MD', '20609', '2013-04-02' );
insert into a_bkorders.customers values (228275, 'Mikulski','Barbara', 'MD', '21203', '2013-04-04' );
insert into a_bkorders.customers values (228352, 'Edwards','Donna', 'MD', '21205', '2013-06-08' );
-- orders and order_details
/* July 2011 */
Insert into a_bkorders.order_headers values(21841, '2011-07-02', 267780);
Insert into a_bkorders.order_details values(21841, 1, 1448, 50, 25.00);
Insert into a_bkorders.order_headers values(21850, '2011-07-02', 261502);
Insert into a_bkorders.order_details values(21850, 1, 1162, 1, 30.49);
Insert into a_bkorders.order_details values(21850, 2, 1109, 1, 25.00);
Insert into a_bkorders.order_headers values(2045, '2011-07-18', 267780);
Insert into a_bkorders.order_details values(2045, 1, 1894, 1, 35.99);
Insert into a_bkorders.order_headers values(2200, '2011-07-18', 261502);
Insert into a_bkorders.order_details values(2200, 1, 1200, 5, 16.33);
Insert into a_bkorders.order_details values(2200, 2, 1180, 5, 45.99);
Insert into a_bkorders.order_details values(2200, 3, 1128, 5, 46.20);
/* Sep 2011 */
Insert into a_bkorders.order_headers values(22909, '2011-09-25', 239427);
Insert into a_bkorders.order_details values(22909, 1, 1104, 5, 45.00);
Insert into a_bkorders.order_headers values(22910, '2011-09-25', 218709);
Insert into a_bkorders.order_details values(22910, 1, 1678, 5, 49.99);
Insert into a_bkorders.order_details values(22910, 2, 1162, 5, 35.00);
Insert into a_bkorders.order_headers values(32997, '2011-09-22', 239427);
Insert into a_bkorders.order_details values(32997, 1, 1948, 5, 40.94);
Insert into a_bkorders.order_details values(32997, 2, 1199, 5, 18.39);
Insert into a_bkorders.order_details values(32997, 3, 1457, 5, 53.99);
Insert into a_bkorders.order_details values(32997, 4, 1133, 5, 18.15);
Insert into a_bkorders.order_details values(32997, 5, 1894, 5, 36.79);
Insert into a_bkorders.order_headers values(32998, '2011-09-22', 261502);
Insert into a_bkorders.order_details values(32998, 1, 2006, 3, 20.00);
Insert into a_bkorders.order_headers values(41005, '2011-09-28', 290298);
Insert into a_bkorders.order_details values(41005, 1, 1142, 2, 42.45);
Insert into a_bkorders.order_details values(41005, 2, 1107, 4, 21.50);
Insert into a_bkorders.order_headers values(41006, '2011-09-28', 267780);
Insert into a_bkorders.order_details values(41006, 1, 1142, 10, 42.95);
Insert into a_bkorders.order_headers values(42899, '2011-09-29', 261502);
Insert into a_bkorders.order_details values(42899, 1, 1128, 5, 25.00);
Insert into a_bkorders.order_details values(42899, 2, 1103, 1 , 10.95);
/* Oct 2011 */
Insert into a_bkorders.order_headers values(21254, '2011-10-23', 263119);
Insert into a_bkorders.order_details values(21254, 2, 2008, 10, 46.95);
Insert into a_bkorders.order_details values(21254, 3, 2007, 10, 39.00);
Insert into a_bkorders.order_headers values(21255, '2011-10-28', 267780);
Insert into a_bkorders.order_details values(21255, 1, 1101, 5, 59.99);
Insert into a_bkorders.order_details values(21255, 2, 1142, 5, 39.00);
Insert into a_bkorders.order_details values(21255, 3, 1162, 2, 35.00);
Insert into a_bkorders.order_headers values(21261, '2011-10-28', 200368);
Insert into a_bkorders.order_details values(21261, 1, 1142, 100, 34.95);
Insert into a_bkorders.order_details values(21261, 2, 1128, 50, 46.95);
Insert into a_bkorders.order_details values(21261, 3, 2001, 100, 39.00);
Insert into a_bkorders.order_headers values(32905, '2011-10-02', 259906);
Insert into a_bkorders.order_details values(32905, 1, 2028, 1, 58.00);
Try this:
SELECT c.cust_id, COUNT(DISTINCT od.book_id) bookCnt
FROM a_bkorders.customers c
INNER JOIN a_bkorders.order_headers oh ON c.cust_id = oh.cust_id
INNER JOIN a_bkorders.order_details od ON oh.order_id = od.order_id
GROUP BY c.cust_id
ORDER BY bookCnt DESC

Needing assitance getting orders in last 2 quarters

I am new to sql and need help with a problem. Can anyone please help?
For each customer with orders in the last two quarters of the previous year, display their total extended cost for each of the last two quarters of the previous year.
A quarter of a year is 3 months- the first quarter is months 1, 2, 3; the second quarter is months 4, 5, 6; the third quarter is months 7, 8, 9; the fourth quarter is months 10, 11, 12. The result set should display one row per customer; the first column is the customer id, the second is the total for quarter 3 and the third column is the total for quarter 4. Display 0 if there are no sales for that customer in that quarter.
Select cust_id
, ifnull(Quarter1, 0) as Quarter1
, ifnull(Quarter2, 0) as Quarter2
FROM a_bkorders.customers
a_bkorders.order_headers using (cust_id)
Join a_bkorders.order_details using (order_id)
where order_id IN
(
Select order_id
FROM a_bkorders.order_details
GROUP BY order_id
Having QUARTER(orders)=
(
Select QUARTER(orders)=1 as Quarter1
, QUARTER(orders)=2 as Quarter2
From(
Select order_id
, sum(order_price * quantity) as orders
FROM a_bkorders.order_details
)tbl
)
);
HERE ARE THE TABLES:
-- create customers
create table a_bkorders.customers (
cust_id integer not null
, cust_name_last varchar(20) not null
, cust_name_first varchar(20) null
, cust_state char(2) not null
, cust_postal_code char(10) not null
, cust_acct_opened date not null
, constraint bk_cust_pk primary key (cust_id)
, constraint bk_cust_id_range check (cust_id > 1000)
, constraint bk_cust_acct_opened_ck check (cust_acct_opened >= '1975-01-01' )
)engine = INNODB;
-- create order_headers
create table a_bkorders.order_headers (
order_id integer not null
, order_date date not null
, cust_id integer not null
, constraint bk_orders_pk primary key (order_id)
, constraint bk_orders_cust_fk foreign key(cust_id)
references a_bkorders.customers(cust_id)
, constraint bk_order_id_range check (order_id > 100)
, constraint bk_order_date_ck check (order_date >= '2000-01-01')
)engine = INNODB;
-- create order_details
create table a_bkorders.order_details (
order_id integer not null
, order_line integer not null
, book_id integer not null
, quantity integer not null
, order_price numeric(6,2) not null
, constraint bk_orderline_pk primary key (order_id, order_line)
, constraint bk_orderline_order_fk foreign key (order_id)
references a_bkorders.order_headers(order_id) on delete cascade
, constraint bk_orderline_book_fk foreign key (book_id )
references a_bkinfo.books(book_id)
, constraint bk_quantity_ck check (quantity > 0)
, constraint bk_ordprice_ck check (order_price >= 0)
)engine = INNODB;
HERE ARE SOME INSERTS:
-- customers
insert into a_bkorders.customers values (208950, 'Adams', 'Samuel', 'MA', '02106', '1996-04-15' );
insert into a_bkorders.customers values (200368, 'Blake', 'William', 'CA', '95959', '1997-07-15' );
insert into a_bkorders.customers values (258595, 'Jobs', 'Peter', 'MA', '02575', '1997-01-09' );
insert into a_bkorders.customers values (263119, 'Jones', null, 'IL', '62979', '1997-03-02' );
insert into a_bkorders.customers values (224038, 'Austin', 'Pat', 'CA', '95900', '1997-08-02' );
insert into a_bkorders.customers values (255919, 'Milton', 'John', 'NJ', '08235', '2011-05-31' );
insert into a_bkorders.customers values (211483, 'Carroll', 'Lewis', 'CA', '94203', '1998-08-08' );
insert into a_bkorders.customers values (221297, 'Dodgson', 'Charles', 'MI', '49327', '2001-05-06' );
insert into a_bkorders.customers values (261502, 'Hawthorne', 'Nathaniel', 'MA', '02297', '2001-10-12' );
insert into a_bkorders.customers values (212921, 'Books on Tap', NULL, 'CA', '94112', '2002-01-06' );
insert into a_bkorders.customers values (260368, 'Muller', 'Jonathan', 'IL', '62885', '2005-12-15' );
insert into a_bkorders.customers values (259969, 'Carlsen', 'Benny', 'NJ', '08505', '2011-07-12' );
insert into a_bkorders.customers values (239427, 'Marksa', 'Anna', 'NJ', '08495', '2011-02-28' );
insert into a_bkorders.customers values (296598, 'Collins', 'Douglas', 'MO', '65836', '2005-04-25' );
insert into a_bkorders.customers values (276381, 'Collins', 'Douglas', 'OH', '22451', '2005-02-08' );
insert into a_bkorders.customers values (234138, 'Keats', 'John', 'IL', '61500', '2006-04-30' );
insert into a_bkorders.customers values (267780, 'Shelly', 'Mary', 'CA', '94100', '2010-10-02' );
insert into a_bkorders.customers values (290298, 'Swift', 'Jonathan', 'MI', '49201', '2010-10-12' );
insert into a_bkorders.customers values (226656, 'Randall', 'Randell', 'NJ', '08251', '2011-08-08' );
insert into a_bkorders.customers values (222477, 'Rossetti', 'Christina', 'MI', '49742', '2011-07-11' );
insert into a_bkorders.customers values (227105, 'Kafka', 'Franz', 'MA', '02297', '2010-12-31' );
insert into a_bkorders.customers values (202958, 'Denver', null, 'IL', '60405', '2011-01-15' );
insert into a_bkorders.customers values (218709, 'Bonnard', 'Paul', 'MA', '02558', '2005-11-15' );
insert into a_bkorders.customers values (217796, 'Anders', null, 'IL', '62505', '2011-03-30' );
insert into a_bkorders.customers values (272787, 'Carlson', 'Ben', 'IL', '62505', '2011-05-05' );
insert into a_bkorders.customers values (234709, 'Brahms', 'Johnnie', 'MA', '02558', '2012-01-15' );
insert into a_bkorders.customers values (217002, 'Grieg', 'Edvard', 'IL', '62329', '2012-02-29' );
insert into a_bkorders.customers values (272611, 'Jarrett', 'Keith', 'IL', '62329', '2011-11-11' );
insert into a_bkorders.customers values (299099, 'Sam', 'Dave', 'CA', '94141', '2011-01-01' );
insert into a_bkorders.customers values (259906, 'Capybara', 'Wile E.', 'CA', '94132', '2012-01-05' );
insert into a_bkorders.customers values (259907, 'Hedge', 'Mr.', 'CA', '94132', '2011-09-05' );
insert into a_bkorders.customers values (282716, 'Biederbecke','Dwight', 'PA', '18106', '2013-01-01' );
insert into a_bkorders.customers values (287261, 'Biederbecke','Bix', 'PA', '18106', '2012-01-01' );
insert into a_bkorders.customers values (226275, 'Dalrymple','Jack', 'SD', '57216', '2013-01-01' );
insert into a_bkorders.customers values (228175, 'Cardin','Benjamin', 'MD', '20609', '2013-04-02' );
insert into a_bkorders.customers values (228275, 'Mikulski','Barbara', 'MD', '21203', '2013-04-04' );
insert into a_bkorders.customers values (228352, 'Edwards','Donna', 'MD', '21205', '2013-06-08' );
-- orders and order_details
/* July 2011 */
Insert into a_bkorders.order_headers values(21841, '2011-07-02', 267780);
Insert into a_bkorders.order_details values(21841, 1, 1448, 50, 25.00);
Insert into a_bkorders.order_headers values(21850, '2011-07-02', 261502);
Insert into a_bkorders.order_details values(21850, 1, 1162, 1, 30.49);
Insert into a_bkorders.order_details values(21850, 2, 1109, 1, 25.00);
Insert into a_bkorders.order_headers values(2045, '2011-07-18', 267780);
Insert into a_bkorders.order_details values(2045, 1, 1894, 1, 35.99);
Insert into a_bkorders.order_headers values(2200, '2011-07-18', 261502);
Insert into a_bkorders.order_details values(2200, 1, 1200, 5, 16.33);
Insert into a_bkorders.order_details values(2200, 2, 1180, 5, 45.99);
Insert into a_bkorders.order_details values(2200, 3, 1128, 5, 46.20);
/* Sep 2011 */
Insert into a_bkorders.order_headers values(22909, '2011-09-25', 239427);
Insert into a_bkorders.order_details values(22909, 1, 1104, 5, 45.00);
Insert into a_bkorders.order_headers values(22910, '2011-09-25', 218709);
Insert into a_bkorders.order_details values(22910, 1, 1678, 5, 49.99);
Insert into a_bkorders.order_details values(22910, 2, 1162, 5, 35.00);
Insert into a_bkorders.order_headers values(32997, '2011-09-22', 239427);
Insert into a_bkorders.order_details values(32997, 1, 1948, 5, 40.94);
Insert into a_bkorders.order_details values(32997, 2, 1199, 5, 18.39);
Insert into a_bkorders.order_details values(32997, 3, 1457, 5, 53.99);
Insert into a_bkorders.order_details values(32997, 4, 1133, 5, 18.15);
Insert into a_bkorders.order_details values(32997, 5, 1894, 5, 36.79);
Insert into a_bkorders.order_headers values(32998, '2011-09-22', 261502);
Insert into a_bkorders.order_details values(32998, 1, 2006, 3, 20.00);
Insert into a_bkorders.order_headers values(41005, '2011-09-28', 290298);
Insert into a_bkorders.order_details values(41005, 1, 1142, 2, 42.45);
Insert into a_bkorders.order_details values(41005, 2, 1107, 4, 21.50);
Insert into a_bkorders.order_headers values(41006, '2011-09-28', 267780);
Insert into a_bkorders.order_details values(41006, 1, 1142, 10, 42.95);
Insert into a_bkorders.order_headers values(42899, '2011-09-29', 261502);
Insert into a_bkorders.order_details values(42899, 1, 1128, 5, 25.00);
Insert into a_bkorders.order_details values(42899, 2, 1103, 1 , 10.95);
/* Oct 2011 */
Insert into a_bkorders.order_headers values(21254, '2011-10-23', 263119);
Insert into a_bkorders.order_details values(21254, 2, 2008, 10, 46.95);
Insert into a_bkorders.order_details values(21254, 3, 2007, 10, 39.00);
Insert into a_bkorders.order_headers values(21255, '2011-10-28', 267780);
Insert into a_bkorders.order_details values(21255, 1, 1101, 5, 59.99);
Insert into a_bkorders.order_details values(21255, 2, 1142, 5, 39.00);
Insert into a_bkorders.order_details values(21255, 3, 1162, 2, 35.00);
Insert into a_bkorders.order_headers values(21261, '2011-10-28', 200368);
Insert into a_bkorders.order_details values(21261, 1, 1142, 100, 34.95);
Insert into a_bkorders.order_details values(21261, 2, 1128, 50, 46.95);
Insert into a_bkorders.order_details values(21261, 3, 2001, 100, 39.00);
Insert into a_bkorders.order_headers values(32905, '2011-10-02', 259906);
Insert into a_bkorders.order_details values(32905, 1, 2028, 1, 58.00);
Try this:
SELECT c.cust_id, SUM(IF(QUARTER(od.orders) = 1, od.order_price * od.quantity, 0)) Quarter1,
SUM(IF(QUARTER(od.orders) = 2, od.order_price * od.quantity, 0)) Quarter2,
SUM(IF(QUARTER(od.orders) = 3, od.order_price * od.quantity, 0)) Quarter3,
SUM(IF(QUARTER(od.orders) = 4, od.order_price * od.quantity, 0)) Quarter4
FROM a_bkorders.customers c
INNER JOIN a_bkorders.order_headers oh ON c.cust_id = oh.cust_id
INNER JOIN a_bkorders.order_details od ON oh.order_id = od.order_id
WHERE YEAR(od.orders) = YEAR(CURRENT_DATE()) - 1
GROUP BY c.cust_id