Subquery as a column : Nested Subquery - mysql

I have two tables 'Student' and 'Team'. i want to display count of student according to Team Name, Team_id from team is primary key.
i tried like this
(SELECT(SELECT team,count(*) as team
FROM student GROUP BY team) AS total,
(SELECT team_name
from team WHERE team_id IN (SELECT team
FROM student GROUP BY team)) as team)
i want output as
Team Name Total Student
-----------------------------
Team 1 25
Team 2 10
Table ' Student'
CREATE TABLE IF NOT EXISTS `student` (
`id` int(255) NOT NULL AUTO_INCREMENT,
`rid` varchar(200) NOT NULL,
`sid` varchar(200) NOT NULL,
`name` varchar(600) NOT NULL,
`age` varchar(200) NOT NULL,
`dob` varchar(200) NOT NULL,
`sex` varchar(200) NOT NULL,
`weight` varchar(200) NOT NULL,
`height` varchar(200) NOT NULL,
`team` varchar(600) NOT NULL,
`age_group` varchar(200) NOT NULL,
`weight_group` varchar(500) NOT NULL,
`belt` varchar(200) NOT NULL,
`black_belt` varchar(200) NOT NULL,
`ikata` varchar(20) NOT NULL,
`ikumite` varchar(20) NOT NULL,
`team_kata` varchar(20) NOT NULL,
`special_entry` varchar(20) NOT NULL,
`challange` varchar(50) NOT NULL,
`state` varchar(200) NOT NULL,
`weapon` varchar(200) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=6 DEFAULT CHARSET=latin1;
Table 'Team'
CREATE TABLE IF NOT EXISTS `team` (
`id` int(20) NOT NULL AUTO_INCREMENT,
`team_id` varchar(500) NOT NULL,
`team_name` varchar(500) NOT NULL,
`address` varchar(500) NOT NULL,
`coach_name` varchar(500) NOT NULL,
`coach_number` varchar(500) NOT NULL,
`coach_email` varchar(500) NOT NULL,
`gold` varchar(200) NOT NULL,
`state` varchar(500) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=4 DEFAULT CHARSET=latin1;

Seems you are looking for this
select a.team_name, count(*)
from team as a
inner join student as b on a.id = b.team
group by a.team_name
(use your proper column for join)

Related

how to match multiple colums of same table and select maximum match colums

SELECT * FROM `student` as s1
LEFT JOIN `student` as s2 ON s1.mainsubject_id=s2.mainsubject_id WHERE s1.mainsubject_id=s2.mainsubject_id AND s1.mainsubject_id > 0 AND s2.mainsubject_id > 0 GROUP BY s1.id`
i have below student table
CREATE TABLE `student` (
`id` int(10) NOT NULL,
`fname` varchar(100) NOT NULL,
`lname` varchar(100) NOT NULL,
`email` varchar(100) NOT NULL,
`mobile` varchar(100) NOT NULL,
`password` varchar(100) NOT NULL,
`mainsubject_id` varchar(50) NOT NULL,
`subsubject_id` varchar(50) NOT NULL,
`level_id` varchar(50) NOT NULL,
`date` varchar(100) NOT NULL,
`postcode` varchar(50) NOT NULL,
`gender` int(1) NOT NULL,
`deleted` int(10) NOT NULL,
`temppassword` varchar(100) NOT NULL,
`stripe_id` text NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
i want to get single record of equal or maximum match from 5 colums (mainsubject_id, subsubject_id, level_id, postcode, gender) in same student table.
what is the best way to get record form same table with maximum match form 5 colums

mysql query to fetch records from multiple tables and join

I have 5 tables named: schools, candidates, candidate_subjects, subjects, lgas
Each school belong to a lga, each candidate belong to a school, each candidate registers subjects
Below are the table structures:
CREATE TABLE `subjects` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(250) CHARACTER SET latin1 COLLATE latin1_bin DEFAULT NULL,
`code` varchar(10) DEFAULT NULL,
`exam_type_id` int(11) DEFAULT NULL,
`status` int(11) DEFAULT NULL,
`type` varchar(3) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=60 DEFAULT CHARSET=latin1;
CREATE TABLE `candidates` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`exam_no` varchar(20) DEFAULT NULL,
`surname` varchar(100) DEFAULT NULL,
`other_names` varchar(150) DEFAULT NULL,
`school_id` int(11) DEFAULT NULL,
`exam_type_id` int(11) DEFAULT NULL,
`dob` varchar(12) DEFAULT NULL,
`sex` varchar(6) DEFAULT NULL,
`no_of_subjects` int(2) DEFAULT NULL,
`nationality` varchar(20) DEFAULT NULL,
`state` varchar(20) DEFAULT NULL,
`lga` varchar(20) DEFAULT NULL,
`exam_year` varchar(4) DEFAULT NULL,
`date_created` varchar(255) DEFAULT NULL,
`date_modified` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
`registration_completed` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=28034 DEFAULT CHARSET=latin1;
CREATE TABLE `candidate_subjects` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`candidate_id` int(11) DEFAULT NULL,
`exam_type_id` int(10) DEFAULT NULL,
`subject_id` int(10) DEFAULT NULL,
`ca_score` int(11) DEFAULT NULL,
`exam_score` int(6) DEFAULT NULL,
`score_grade` varchar(10) DEFAULT NULL,
`date_created` varchar(10) DEFAULT NULL,
`date_modified` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=327740 DEFAULT CHARSET=latin1;
CREATE TABLE `schools` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`passcode` varchar(15) DEFAULT NULL,
`code` varchar(10) DEFAULT NULL,
`name` varchar(200) DEFAULT NULL,
`lga` int(11) DEFAULT NULL,
`address` varchar(250) DEFAULT NULL,
`phone` varchar(50) DEFAULT NULL,
`exam_year` varchar(10) DEFAULT NULL,
`eo_name` varchar(100) DEFAULT NULL,
`eo_phone` varchar(50) DEFAULT NULL,
`eo_email` varchar(100) DEFAULT NULL,
`date_created` varchar(10) DEFAULT NULL,
`date_modified` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
`profile_created` int(1) DEFAULT NULL,
`entries_purchased` int(11) DEFAULT NULL,
`entries_used` int(11) DEFAULT NULL,
`entries_remaining` int(11) DEFAULT NULL,
`scratchcard_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=652 DEFAULT CHARSET=latin1;
CREATE TABLE `lgas` (
`lga_id` int(11) NOT NULL AUTO_INCREMENT,
`lga_name` varchar(250) NOT NULL,
`state_id` varchar(20) NOT NULL,
PRIMARY KEY (`lga_id`)
) ENGINE=InnoDB AUTO_INCREMENT=786 DEFAULT CHARSET=latin1;
I want to generate a report for each lga like this:
S/No| Name of School |Eng|Mth|B.sc|....Total registered
That is name of school from the selected lga, total number of students from that school that registered for Eng, Mth, B.sc ... Total number of students that registered those subjects from that school
SELECT
b.name as school_name,
sum(case when e.name = 'Eng' then 1 else 0 end) as english_students,
sum(case when e.name = 'Mth' then 1 else 0 end) as math_students,
sum(case when e.name = 'B.sc' then 1 else 0 end) as whatever_this_is_students
FROM lgas a
LEFT JOIN schools b ON a.lga_id = b.lga
LEFT JOIN candidates c on b.id = c.school_id
LEFT JOIN candidate_subjects d on c.id = d.candidate_id
LEFT JOIN subjects e on d.subject_id = e.id
WHERE a.lda_id = 'selected_id'
GROUP by school_name;

SQL UNION with Where clause a result of the first select

I need to execute the following query:
SELECT (COL1,COL2, ClientID)
FROM Jobs
Union
SELECT (ClientID,COL2,COL3)
FROM Clients WHERE (the ClientID= ClientID my first select)
I'm really stuck, I've been trying joins and unions and have no idea how to do this.
*EDIT*Query to create jobs table
CREATE TABLE IF NOT EXISTS `jobs` (
`JobID` int(11) NOT NULL AUTO_INCREMENT,
`Title` varchar(32) NOT NULL,
`Trade` varchar(32) NOT NULL,
`SubTrade` varchar(300) NOT NULL,
`Urgency` tinyint(4) NOT NULL,
`DatePosted` int(11) NOT NULL,
`Description` varchar(500) NOT NULL,
`Photo` longblob,
`Photo2` longblob,
`Address` varchar(600) NOT NULL,
`ShowAddress` tinyint(4) NOT NULL,
`ShowExact` tinyint(4) NOT NULL,
`JobStatus` tinyint(4) NOT NULL,
`Longitude` double NOT NULL,
`Latitude` double NOT NULL,
`ClientID` int(11) NOT NULL,
`TradesmanID` int(11) DEFAULT NULL,
PRIMARY KEY (`JobID`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=171 ;
and query to create clients table is
CREATE TABLE IF NOT EXISTS `clients` (
`ClientID` int(11) NOT NULL AUTO_INCREMENT,
`FName` varchar(32) NOT NULL,
`SName` varchar(32) NOT NULL,
`Email` varchar(32) NOT NULL,
`HomePhone` int(11) NOT NULL,
`Mobile` varchar(30) NOT NULL,
`Address` varchar(100) NOT NULL,
`County` varchar(32) NOT NULL,
`PostCode` varchar(32) NOT NULL,
`UserName` varchar(32) NOT NULL,
`Password` varchar(32) NOT NULL,
`NotificationID` varchar(255) NOT NULL,
PRIMARY KEY (`ClientID`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=96 ;
SELECT
Clients.ClientID
,Clients.NotificationID
,Clients.Email
,Clients.Mobile
,Clients.HomePhone
,Jobs.JobID
,Jobs.Title
,Jobs.Trade
,Jobs.Address AS JobAddress
,Jobs.Urgency
,Jobs.DatePosted
,Jobs.Description
,Jobs.Photo
,Jobs.Photo2
,Jobs.ShowAddress
,Jobs.ShowExact
,Jobs.JobStatus
,Jobs.TradesmanID
,Jobs.Longitude
,Jobs.Latitude
FROM
Clients
INNER JOIN
Jobs
on Clients.ClientId = Jobs.ClientId
How about this? There is a bit of duplication i.e. the select clause in the second union replications the first statement but it will work.
SELECT COL1,COL2, ClientID
FROM Jobs
Union
SELECT ClientID,COL2,COL3
FROM Clients WHERE (Select ClientID FROM Jobs)
try this:
SELECT c.ClientID, c.COL2, c.COL3, x.col1
FROM Clients c inner join
(select clientId,
min(col1) as col1
from jobs
group by clientId) x
on c.clientId = x.clientId

How to optimize a MySQL JOIN Query

I have this MySQL query that I want to optimize:
SELECT r.WarehouseLocation,sum(sir.qty)
FROM repairableissue as r
INNER JOIN SIR ON r.sirno=sir.sirno
AND r.region=sir.region
AND r.ItemName=sir.Itemdesc
AND r.SerialNo=sir.Serialno
WHERE r.status='Pending'
GROUP BY r.warehouseLocation
How do I optimize this query? I read about optimization and found out that indexes might help but still could not achieve the desired performance.
Which index should be used and which should be removed?
Below is the explain of query:
Repairableissue
CREATE TABLE `repairableissue` (
`Vendor` varchar(40) NOT NULL,
`ItemName` varchar(200) NOT NULL,
`SerialNo` varchar(50) NOT NULL,
`person` varchar(200) NOT NULL,
`siteid` varchar(10) NOT NULL,
`invuser` varchar(50) NOT NULL,
`region` varchar(50) NOT NULL,
`id` int(11) NOT NULL AUTO_INCREMENT,
`Dated` date NOT NULL,
`Sirno` varchar(50) NOT NULL,
`status` varchar(30) NOT NULL DEFAULT 'Pending',
`trackthrough` varchar(30) NOT NULL,
`reason` varchar(100) NOT NULL,
`ckh` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`WarehouseType` varchar(20) NOT NULL,
`WarehouseLocation` varchar(20) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `id` (`id`),
KEY `I1` (`status`),
KEY `ind2` (`ItemName`),
KEY `ind3` (`region`),
KEY `ind5` (`SerialNo`),
KEY `ind4` (`Sirno`)
) ENGINE=MyISAM AUTO_INCREMENT=63029 DEFAULT CHARSET=latin1
sir
CREATE TABLE `sir` (
`SirNo` varchar(50) NOT NULL,
`SiteId` varchar(80) NOT NULL,
`Vendor` varchar(70) NOT NULL,
`Type` varchar(15) NOT NULL,
`ItemDesc` varchar(200) NOT NULL,
`ItemCode` varchar(25) NOT NULL,
`SerialNo` varchar(50) NOT NULL,
`Unit` varchar(15) NOT NULL,
`AssetCode` varchar(50) NOT NULL,
`Qty` decimal(11,0) NOT NULL,
`Region` varchar(15) NOT NULL,
`Status` varchar(20) NOT NULL DEFAULT 'Installed',
`FaultInfo` varchar(100) NOT NULL DEFAULT 'date()',
`chk` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`Phase` varchar(15) NOT NULL,
`Category` varchar(200) NOT NULL,
`Issue_Vendor` varchar(30) NOT NULL,
`AssetName` varchar(150) NOT NULL,
`Ownership` varchar(20) NOT NULL,
`Dated` date NOT NULL,
`PersonName` varchar(150) NOT NULL,
`Remarks` varchar(300) NOT NULL,
`po` varchar(100) NOT NULL,
`invuser` varchar(50) NOT NULL,
`id` int(11) NOT NULL AUTO_INCREMENT,
`grnno` varchar(30) NOT NULL,
`WarehouseType` varchar(20) NOT NULL,
`WarehouseLocation` varchar(20) NOT NULL,
`mainpartserial` varchar(200) NOT NULL,
PRIMARY KEY (`Vendor`,`Type`,`ItemCode`,`ItemDesc`,`SerialNo`,`Ownership`,`SirNo`,`Region`,`WarehouseType`,`WarehouseLocation`,`po`,`Qty`,`id`),
KEY `id` (`id`),
KEY `ind4` (`ItemDesc`),
KEY `ind6` (`SerialNo`),
KEY `ind7` (`SerialNo`)
) ENGINE=MyISAM AUTO_INCREMENT=228007 DEFAULT CHARSET=latin1
One multi-column index on r.status + r.warehouseLocation, in that order.
One multi-column index on sir.sirno + sir.region + sir.Itemdesc + sir.Serialno, in order of most cardinality to least cardinality, with sir.qty tacked on the end.
This assumes the fields are small enough to fit (combined) into an index.
Still, join seeks are unavoidable. The number of records that match r.status='Pending' is going to dictate the speed of this query.

create table from two existing table by making the index column and value not match in both table

for this table1 structure is:
CREATE TABLE `table1` (
`table_id` int(11) NOT NULL auto_increment,
`firstname` varchar(25) default NULL,
`column2` varchar(32) default NULL,
`column3` varchar(25) default NULL,
`column4` varchar(25) default NULL,
`column5` varchar(56) default NULL,
`column6` varchar(25) default NULL,
`column7` varchar(36) default NULL,
`column8` varchar(25) default NULL,
`column9` varchar(40) default NULL,
`column10` varchar(86) default NULL,
`column11` varchar(113) default NULL,
`column12` varchar(50) default NULL,
`column13` varchar(50) default NULL,
`column14` varchar(25) default NULL,
`column15` varchar(25) default NULL,
`column16` varchar(25) default NULL,
`column17` varchar(25) default NULL,
`column18` varchar(25) default NULL,
PRIMARY KEY (`table_id`),
KEY `firstname` (`firstname`),
) ENGINE=MyISAM AUTO_INCREMENT=13982 DEFAULT CHARSET=utf8;
CREATE TABLE `table2` (
`table_id` int(11) NOT NULL auto_increment,
`firstname` varchar(25) default NULL,
`column2` varchar(32) default NULL,
`column3` varchar(25) default NULL,
`column4` varchar(25) default NULL,
`column5` varchar(56) default NULL,
`column6` varchar(25) default NULL,
`column7` varchar(36) default NULL,
`column8` varchar(25) default NULL,
`column9` varchar(40) default NULL,
`column10` varchar(86) default NULL,
`column11` varchar(113) default NULL,
`column12` varchar(50) default NULL,
`column13` varchar(50) default NULL,
`column14` varchar(25) default NULL,
`column15` varchar(25) default NULL,
`column16` varchar(25) default NULL,
`column17` varchar(25) default NULL,
`column18` varchar(25) default NULL,
PRIMARY KEY (`table_id`),
KEY `firstname` (`firstname`),
) ENGINE=MyISAM AUTO_INCREMENT=13982 DEFAULT CHARSET=utf8;
after this executing this below query and its giving timeout expired in code.
CREATE TABLE new_tablematch
select table_id, firstname
from table1
where firstname NOT in (select a.firstname
from table1 as a , table2 as b
where a.firstname= b.firstname);
Try this query:
CREATE TABLE new_tablematch
SELECT table1.table_id, table1.firstname
FROM table1 LEFT JOIN table2 ON table1.firstname = table2.firstname
WHERE table2.firstname IS NULL;
It should have a better performance than your query (you are referring to table1 twice, and the subselect might be executed for every row of table1).
The problem with your query is that you mention table1 twice. It is not needed in the subquery:
CREATE TABLE new_tablematch
select table_id, firstname
from table1
where firstname NOT in (select b.firstname
from table2 as b
);
However, the join version in the other answer might perform even better.