SQL query; inner join on 4 tables - mysql

Is this the most efficient way of joining these 4 tables? Also is it possible to only have some rows of each tables selected? I tried changing * to a name of a column but only the columns from studentlist are allowed.
SELECT c.classID, c.instrument, c.grade, u.ID, u.firstname, u.lastname, u.lastsongplayed, u.title
FROM studentlist s
INNER JOIN classlist c ON s.listID = c.classID
INNER JOIN (
SELECT *
FROM users u
INNER JOIN library l ON u.lastsongplayed = l.fileID
)
u ON s.studentID = u.ID
WHERE teacherID =3
ORDER BY classID
LIMIT 0 , 30
Database structure:
CREATE TABLE IF NOT EXISTS `classlist` (
`classID` int(11) NOT NULL AUTO_INCREMENT,
`teacherID` int(11) NOT NULL,
`instrument` text,
`grade` int(11) DEFAULT NULL,
PRIMARY KEY (`classID`),
KEY `teacherID_2` (`teacherID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=27 ;
CREATE TABLE IF NOT EXISTS `studentlist` (
`listID` int(11) NOT NULL,
`studentID` int(11) NOT NULL,
KEY `teacherID` (`studentID`),
KEY `studentID` (`studentID`),
KEY `listID` (`listID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `users` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`email` varchar(60) NOT NULL,
`password` varchar(60) NOT NULL,
`firstname` text NOT NULL,
`lastname` text NOT NULL,
`sessionID` varchar(60) DEFAULT NULL,
`lastlogin` time DEFAULT NULL,
`registerdate` date NOT NULL,
`isteacher` tinyint(1) DEFAULT NULL,
`isstudent` tinyint(1) DEFAULT NULL,
`iscomposer` tinyint(1) DEFAULT NULL,
`lastsongplayed` int(11) NOT NULL,
PRIMARY KEY (`ID`),
UNIQUE KEY `ID` (`ID`),
UNIQUE KEY `email` (`email`,`sessionID`),
KEY `ID_2` (`ID`),
KEY `ID_3` (`ID`),
KEY `lastsongplayed` (`lastsongplayed`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=63 ;
CREATE TABLE IF NOT EXISTS `library` (
`fileID` int(11) NOT NULL AUTO_INCREMENT,
`userID` int(11) NOT NULL,
`uploaddate` datetime NOT NULL,
`title` varchar(60) NOT NULL,
`OrigComposer` varchar(60) NOT NULL,
`composer` varchar(60) NOT NULL,
`genre` varchar(60) DEFAULT NULL,
`year` year(4) DEFAULT NULL,
`arrangement` varchar(60) DEFAULT NULL,
PRIMARY KEY (`fileID`),
KEY `userID` (`userID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=77 ;

Is this the most efficient way of joining these 3 tables?
Your JOIN looks correct and you are joining on your keys. So this should be efficient. However, I would encourage you to analyze your query with EXPLAIN to determine additional optimizations.
Is it possible to only have some rows of each tables selected?
Yes. Change * to be the columns from each table you want. I encourage you to explicitly prefix them with the originating table. Depending on the columns you select, this could also make your query more performant.
SELECT studentlist.studentID, users.email FROM ...

Related

MySql Using filesort when i using a group by

I have a little problem with optimizing a query, I have 2 tables, one which records the participation (participation) in a quiz, and the other which records the answer to each question (participation_rep), participation is linked to the campaign table.
SELECT count(DISTINCT p.id) as number_of_participation
FROM participation_rep prep
INNER JOIN participation p
ON p.id = prep.id_participation
AND p.trash <> 1
WHERE prep.id_question IN (780,787,794,801,809)
AND prep.trash <> 1
GROUP BY pp.id_campaign
Explain of the query
And the problem is that this request is very heavy to execute when there is a lot of data which is concerned by the request and I do not know how to optimize it.
This query take 30-50ms to execute.
Structure of table participation :
CREATE TABLE IF NOT EXISTS `participation` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`id_campagne` int(11) NOT NULL,
`id_identifiant` int(11) DEFAULT NULL,
`firstname` varchar(255) DEFAULT NULL,
`surname` varchar(255) DEFAULT NULL,
`email` varchar(255) DEFAULT NULL,
`date_p` date NOT NULL,
`hour_p` time NOT NULL,
`comment` text,
`trash` tinyint(1) DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Structure of table participation_rep :
CREATE TABLE IF NOT EXISTS `participation_rep` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`id_participation` int(11) NOT NULL,
`id_question` int(11) NOT NULL,
`id_rep` int(11) NOT NULL,
`trash` tinyint(1) DEFAULT '0',
PRIMARY KEY (`id`),
UNIQUE KEY `id_participation` (`id_participation`,`id_question`,`id_reponse`),
KEY `id_question` (`id_question`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Spped up MySQL query

I need help speeding up a MySQL query that's running extremely slowly. It's taking over 35 seconds to return 900 rows.
Does anyone have ideas how I can speed things up on this query?
Many thanks in advance
select products.*,
p.price as lowest_price,
products_images.thumbnail
from products
inner join products_categories on products_categories.product_id = products.id
inner join products_colours on products_colours.product_id = products.id
inner join products_quantity_pricing on products_quantity_pricing.product_id = products.id
left join ( select min(price) as price, product_id from products_quantity_pricing group by products_quantity_pricing.product_id ) as p on p.product_id = products.id
inner join products_images on products_images.product_id = products.id
where products.id > 0 group by products.id
order by products.product_name
Here is the setup of the tables involved:
CREATE TABLE IF NOT EXISTS `products_categories` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`product_id` smallint(5) unsigned zerofill NOT NULL,
`category` int(11) NOT NULL,
`sub_category` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1016 ;
CREATE TABLE IF NOT EXISTS `products` (
`product_prefix` varchar(10) NOT NULL,
`id` smallint(5) unsigned zerofill NOT NULL AUTO_INCREMENT,
`supplier_id` int(11) NOT NULL,
`product_code` varchar(50) NOT NULL,
`supplier_product_code` mediumtext NOT NULL,
`product_name` varchar(200) NOT NULL,
`product_description` text NOT NULL,
`print_area` varchar(100) DEFAULT NULL,
`print_position` varchar(100) DEFAULT NULL,
`dimensions` varchar(100) DEFAULT NULL,
`origination` tinytext,
`unit_cost` decimal(9,2) NOT NULL,
`updated` datetime NOT NULL,
`url` varchar(255) NOT NULL,
PRIMARY KEY (`id`),
KEY `product_code` (`product_code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=901 ;
CREATE TABLE IF NOT EXISTS `products_images` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`product_id` smallint(5) unsigned zerofill NOT NULL,
`fullsize` varchar(255) NOT NULL,
`midsize` varchar(255) NOT NULL,
`thumbnail` varchar(255) NOT NULL,
`updated` datetime NOT NULL,
`colour_tag` varchar(100) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=2402 ;
CREATE TABLE IF NOT EXISTS `products_colours` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`product_id` smallint(5) unsigned zerofill NOT NULL,
`colour` varchar(100) NOT NULL,
PRIMARY KEY (`id`),
KEY `product_id` (`product_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=2546 ;
CREATE TABLE IF NOT EXISTS `products_quantity_pricing` (
`product_id` smallint(5) unsigned zerofill NOT NULL,
`quantity` smallint(6) NOT NULL,
`price` decimal(9,2) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Add indexes on the product_id columns in all the tables.
In the products_quantity_pricing, a composite index on (product_id, price) will also speed up finding the minimum price for each product. If you create this composite index, you don't need to create a separate index just on product_id; the prefix of a composite index also serves as an index of its own.

fix Using index, Using temporary, Using filesort

i have such 3 tables. Im trying to Left Join them
SELECT `t`.`title` AS `category_title`,`t`.`id` AS `category_id`, `st`.`title` AS
`subcategory_title`, `st`.`id` AS `subcategory_id`, `st`.`parent_id` AS
`subcategory_parent`, `n`.`title` AS `news_title`,`n`.`id` AS `news_id` FROM
`t_categories` `t` LEFT JOIN t_categories AS `st` ON `st`.`parent_id`=t.`id` LEFT JOIN
t_newsrelations AS `nr` ON `nr`.`category_id`=st.`id` LEFT JOIN t_news AS `n` ON
`n`.`id`=nr.`news_id` WHERE `t`.`enabled` = 1 AND `n`.`enabled` = 1 AND `n`.`type`!=1 AND
`n`.`type`!=5 ORDER BY `t`.`position`,`st`.`position`,`n`.`position` ASC
here is the structure of tables
CREATE TABLE IF NOT EXISTS `t_categories` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`parent_id` int(11) NOT NULL,
`title` tinytext NOT NULL,
`position` tinyint(4) unsigned NOT NULL DEFAULT '0',
`type` tinyint(1) unsigned NOT NULL,
`enabled` tinyint(1) unsigned NOT NULL DEFAULT '1',
UNIQUE KEY `id` (`id`),
KEY `type` (`type`),
KEY `parent_id` (`parent_id`),
KEY `enabled` (`enabled`),
KEY `id_parent_position_enabled` (`id`,`parent_id`,`position`,`enabled`),
KEY `position` (`position`),
KEY `parent_id_2` (`parent_id`,`enabled`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 ;
CREATE TABLE IF NOT EXISTS `t_news` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`title` tinytext NOT NULL,
`m_title` tinytext NOT NULL,
`url` varchar(2000) NOT NULL,
`keywords` text NOT NULL,
`description` text NOT NULL,
`body` longtext NOT NULL,
`position` tinyint(4) unsigned NOT NULL DEFAULT '0',
`type` tinyint(1) unsigned NOT NULL,
`city_id` int(4) NOT NULL,
`quickmenu_enabled` tinyint(1) unsigned NOT NULL DEFAULT '0',
`quickmenu` text NOT NULL,
`enabled` tinyint(1) unsigned NOT NULL DEFAULT '1',
PRIMARY KEY (`id`),
UNIQUE KEY `id` (`id`),
KEY `position` (`position`),
KEY `type` (`type`),
KEY `city_id` (`city_id`),
KEY `url` (`url`(333)),
KEY `quickmenu_enabled` (`quickmenu_enabled`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 ;
CREATE TABLE IF NOT EXISTS `t_newsrelations` (
`category_id` int(11) NOT NULL,
`news_id` int(11) unsigned NOT NULL,
KEY `category_id` (`category_id`),
KEY `news_id` (`news_id`),
KEY `category_id_2` (`category_id`,`news_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
And SELECT EXPLAIN shows me
t_newsrelations is intermediate table. Table t_categories contains categories and subcategories linked by parent_id column. Each item from t_news can be a member of more than one subcategories thats why they linked through t_newsrelations
how to optimise a query? Why it shows Using index, Using temporary, Using filesort?
ORDER BY `t`.`position`,`st`.`position`,`n`.`position` ASC
You can't eliminate the temp table and filesort in this query, given the tables you have, because you're sorting on columns from multiple tables. Optimizing sorting means using an index so that the query fetches rows in the order you want them. But there's no way in MySQL to create an index that spans multiple tables.
The only way to fix this is to denormalize until all three columns are in a single table, and create one index over the three columns. But denormalization comes with its own downsides.

Query data from two tables does not work, query only a single tables works

Here is my export.
CREATE TABLE IF NOT EXISTS `table1` (
`order_id` int(7) NOT NULL DEFAULT '0',
`order_date` varchar(8) DEFAULT NULL,
`tkt_order_id` int(9) DEFAULT NULL,
`event_date` varchar(8) DEFAULT NULL,
`event_name` varchar(6) DEFAULT NULL,
`event_year` int(4) DEFAULT NULL,
`mail` varchar(60) NOT NULL,
`quantity` int(3) DEFAULT NULL,
`ticket_type` varchar(7) DEFAULT NULL,
`ticket_days` varchar(9) DEFAULT NULL,
`ticket_subtype` varchar(18) DEFAULT NULL,
`base` varchar(10) DEFAULT NULL,
`service` varchar(10) DEFAULT NULL,
`gross` varchar(10) DEFAULT NULL,
PRIMARY KEY (`order_id`),
UNIQUE KEY `order_id` (`order_id`) USING BTREE,
KEY `email` (`mail`,`order_date`,`event_name`,`event_year`,`quantity`,`ticket_type`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `table2` (
`mail` varchar(60) NOT NULL DEFAULT '',
`first_name` varchar(27) DEFAULT NULL,
`lastname` varchar(20) DEFAULT NULL,
`address` varchar(63) DEFAULT NULL,
`address2` varchar(38) DEFAULT NULL,
`city` varchar(27) DEFAULT NULL,
`state` varchar(22) DEFAULT NULL,
`zip` varchar(10) DEFAULT NULL,
`country` varchar(20) DEFAULT NULL,
`phone` varchar(16) DEFAULT NULL,
PRIMARY KEY (`mail`),
UNIQUE KEY `mail` (`mail`) USING BTREE,
KEY `index` (`first_name`,`lastname`,`city`,`state`,`zip`,`country`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
ALTER TABLE `table1`
ADD CONSTRAINT `table1_ibfk_1` FOREIGN KEY (`mail`) REFERENCES `table2` (`mail`) ON DELETE NO ACTION ON UPDATE NO ACTION;
You forgot to include the meaningful link on the foreign key in your where-clause:
db.sales.mail = db.customers.mail
Also, use brackets to group your conditions together. Something like cond1 OR cond2 AND cond3 will probably not work as expected, so for example you could write this as (cond1 OR cond2) AND cond3.
So something like this should work:
SELECT db.customers.first_name,
db.customers.last_name,
db.customers.mail,
db.sales.event_year,
db.sales.ticket_type,
db.sales.event_name
FROM db.sales, db.customers
WHERE db.sales.mail = db.customer.mail
AND (db.sales.ticket_type = "ticket1"
OR db.sales.ticket_type = "ticket2"
OR db.sales.ticket_type = "ticket3")
AND (db.sales.event_year=2009
OR db.sales.event_year=2010)
While the above should work, it's better to write it like this (mostly for readability):
SELECT c.first_name,
c.last_name,
c.mail,
s.event_year,
s.ticket_type,
s.event_name
FROM db.sales s
INNER JOIN db.customer c ON s.mail = c.mail
WHERE s.ticket_type IN ('ticket1','ticket2','ticket3')
AND s.event_year IN (2009,2010);
Note: I simply removed the final GROUP BY in your query, since I don't know what you're trying to accomplish with that. If you use GROUP BY, it should be on at least all selected columns that are not aggregate functions (like SUM, COUNT etc.)
Use left join instead of inner join. Eg:
SELECT c.*, s.*
FROM customers c
LEFT JOIN sales s ON s.email = c.email;

Get same IDs from Detail Table

I have 2 tables in my mysql database:
CREATE TABLE IF NOT EXISTS `RECIPES` (
`recipes_id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(50) COLLATE utf8_bin NOT NULL,
`text` varchar(2000) COLLATE utf8_bin NOT NULL,
`count_persons` int(11) NOT NULL,
`duration` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
`date` datetime NOT NULL,
`accepted` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`recipes_id`),
KEY `recipes_user_fk` (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin AUTO_INCREMENT=88 ;
CREATE TABLE IF NOT EXISTS `RECIPES_POS` (
`recipes_pos_id` int(11) NOT NULL AUTO_INCREMENT,
`recipes_id` int(11) NOT NULL,
`ingredients_id` int(11) NOT NULL,
`ingredients_value` int(11) NOT NULL,
PRIMARY KEY (`recipes_pos_id`),
KEY `recipe_pos_rec_id` (`recipes_id`),
KEY `recipes_pos_ingredient_fk` (`ingredients_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=58 ;
In the Recipe_Pos Table are many entries. This table shows what ingredients are used in the Recipe.
Now i want to find the recipe which contains incredients like powder and sugar:
SELECT r.recipes_id FROM RECIPES r, RECIPES_POS rp WHERE r.recipes_id = rp.recipes_id AND rp.ingredients_id =6 AND rp.ingredients_id =4
this statment is wrong because a entry in Recipe_Pos can'T contains both incredients.
Whats the right query? It should works with only 1 incredient and more
select r.recipes_id
from RECIPES r
inner join RECIPES_POS rp on r.recipes_id = rp.recipes_id
where rp.ingredients_id in (4, 6)
group by r.recipes_id
having count(distinct rp.ingredients_id) = 2