Related
I have 2 tables.
How do i search for all rows in the first table that has no reference in the second table.
The connection field is: res_srvs.id = inv_supp2srv.srvID
So, I want to get all table "res_srvs" rows that has no srvID in table "inv_supp2srv".
TABLE: res_srvs
Collation Attributes
id int(11)
clientID int(6)
resNum int(9)
net decimal(7,2)
tax decimal(7,2)
from_date(date)
TABLE: inv_supp2srv
Collation Attributes
clientID int(6)
invNum int(10)
srvID int(11)
amount decimal(7,2)
valid tinyint(1)
This is what i tried:
SELECT srv.net , srv.tax , srv.net+srv.tax AS amount, srv.id AS srv_id
FROM res_srvs AS srv , inv_supp2srv AS i2s
WHERE srv.clientID = 1
AND srv.from_date >= '2020-03-01'
AND i2s.clientID = 1
AND i2s.srvID = srv.id
AND (NOT EXISTS
(
SELECT *
FROM inv_supp2srv AS i2s
WHERE i2s.srvID = srv.id
)
)
What you want is a left outer join with exclusion :
SELECT r.*
FROM res_srvs r
LEFT JOIN inv_supp2srv i
ON r.id = i.srvID
WHERE i.srvID IS NULL
AND (
-- Your others where clauses go there
);
You can use LEFT JOIN for second table and filter by NULL joined value like:
SELECT srv.net , srv.tax , srv.net+srv.tax AS amount, srv.id AS srv_id
FROM res_srvs AS srv
LEFT JOIN inv_supp2srv AS i2s ON i2s.srvID = srv.id
WHERE
srv.clientID = 1
AND srv.from_date >= '2020-03-01'
-- AND i2s.clientID = 1 not relevant condition
AND i2s.srvID IS NULL;
Another approach is using NOT EXISTS condition:
SELECT srv.net , srv.tax , srv.net+srv.tax AS amount, srv.id AS srv_id
FROM res_srvs AS srv
WHERE
srv.clientID = 1
AND srv.from_date >= '2020-03-01'
AND NOT EXISTS (
SELECT srvID FROM inv_supp2srv AS i2s WHERE i2s.srvID = srv.id
);
I want to get all table res_srvs rows that have no srvID in table inv_supp2srv.
It looks like you are overcomplicating this. I don't see the point for the join between the tables in the outer query - it attempts to match the tables, which contradicts the not exists condition.
I think you just want:
select r.*
from res_srvs r
where
r.from_date >= '2020-03-01'
and r.clientID = 1
and not exists (
select 1
from inv_supp2srv i
where i.srvID = r.id and i.clientID = r.clientID
)
I am unsure whether you want clientID in the correlation clause or not - your query makes it look like it is the case, so I added it.
I've a SELECT which checks a status of active alarms (icinga).
This select joins different tables and until here all ok.
On the result I've as value/column an object_id as well. I would like to add a column to that select that could be empty or not, because, searching that 'object_id' on a different table, I could get a value or not. This accessory table is structured having: object_id, varname, varvalue.
So, i.e., my SELECT returns those values:
`name`, `object_id`, `status`
`Hello`, `123456`, `OK`
I would add the column City that should compared to a table having:
`object_id`, `varname`, `varvalue`
`123456`, `city`, `Rome`
`123456`, `lake`, `Garda`
`789789`, `city`, `Milano`
So that if the second table has object_id = 123456 AND city = Rome the result should be:
`name`, `object_id`, `status`, `city`
`Hello`, `123456`, `OK`, `Rome`
Otherwise the result should be:
`Hello`, `123456`, `OK`, `UNKNOWN`
How to do that?
Hope I've explained it well :-)
Thanks!
* EDIT *
It's better I explain with real example. My query actually is the following:
select icinga_objects.object_id, icinga_objects.name1 as host_name, icinga_objects.name2 as ServiceName, "service" as Type, icinga_servicestatus.last_check as LastCheckTime, icinga_servicestatus.last_hard_state_change as LastStateChange, TIMEDIFF(now(), icinga_servicestatus.last_hard_state_change) AS SinceTime,
CASE
WHEN icinga_servicestatus.current_state = 0 THEN '0'
WHEN icinga_servicestatus.current_state = 1 THEN '2'
WHEN icinga_servicestatus.current_state = 2 THEN '3'
ELSE '3'
END AS state
FROM icinga_objects, icinga_servicestatus, icinga_services WHERE icinga_servicestatus.service_object_id IN
(SELECT service_object_id FROM icinga_services WHERE icinga_services.host_object_id IN
(SELECT host_object_id FROM icinga_hostgroup_members WHERE hostgroup_id IN
(SELECT hostgroup_id FROM icinga_hostgroups WHERE alias = 'MY-HOSTGROUP-TO-FILTER')
)
)
AND icinga_servicestatus.service_object_id NOT IN
(SELECT service_object_id FROM icinga_services WHERE icinga_services.service_object_id IN (
SELECT object_id FROM icinga_objects WHERE icinga_objects.is_active = 1 AND icinga_objects.object_id IN
(SELECT object_id FROM icinga_customvariables WHERE varvalue = '8x5')
)
)
AND icinga_servicestatus.last_check > NOW() - INTERVAL 3 HOUR
AND icinga_servicestatus.state_type = 1
AND icinga_servicestatus.scheduled_downtime_depth = 0
AND icinga_objects.object_id = icinga_services.service_object_id
AND icinga_servicestatus.service_object_id = icinga_services.service_object_id
AND icinga_servicestatus.current_state = 2
AND icinga_servicestatus.problem_has_been_acknowledged = 0
This gives me as result, in example:
`object_id`, `host_name`, `ServiceName`, `Type`, `LastCheckTime`, `LastStateChange`, `SinceTime`, `State`
`123456`, `myHostName`, `myServiceName`, `service`, `2020-04-29 17:19:21`, `2020-04-28 14:50:27`, `26:32:51`, `3`
Here I would like to add the column.
So, now if I search object_id into icinga_customvariables I could find entries, or not. In Example, searching object_id = 123456 I have 4 records, but ONLY one having varname = NAME_IM_SEARCHING and so I need to add to the above result the corresponding of varvalue searching icinga_customvariables.object_id = '123456' AND varname = NAME_IM_SEARCHING. IF there are NO results, then the added cloumn should be UNKNOWN, otherwise the added column should be = icinga_customvariables.varvalue.
How to add it? :-)
You can place your query into a "table expression" so it becomes simpler to join it to the other_table. For example:
select
q.*,
coalesce(o.varvalue, 'UNKNOWN') as city
from (
-- your existing query here
) q
left join other_table o on o.object_id = q.object_id and o.varname = 'city'
EDIT: Joining multiple times
As requested if you need to extract more city names using another column, or if you want to extract against another table altogether, you can add an extra LEFT JOIN. For example:
select
q.*,
coalesce(o.varvalue, 'UNKNOWN') as city,
coalesce(o2.varvalue, 'UNKNOWN') as lake
from (
-- your existing query here
) q
left join other_table o on o.object_id = q.object_id and o.varname = 'city'
left join other_table o2 on o.object_id = q.object_id and o2.varname = 'lake'
I am finding a hard time to summarize the SQL table.
Objective: from the given tables I have to join and summarize the table.
col1 = Name_of_student,
col2 = Name_of_subject(where she/he scored highest),
col3= highest_number,
col4 = faculty_Name(where she/he scored highest),
col5 = Name_of_subject(where she/he scored lowest),
col6 = lowest marks,
col7 = faculty_Name(where she/he scored lowest)
Note - I have to write only one query for the given output.
There four tables:
Students.
Students_subject.
Faculty.
Marks.
You can copy the code in my SQL script for understanding the tables.
create database university ;
use university ;
create table students (id int auto_increment primary key,
student_name varchar(250) NOT NULL,
dob DATE NOT NULL) ;
create table faculty ( id int auto_increment primary key,
faculty_name varchar(250) NOT NULL,
date_of_update datetime default NOW()) ;
create table Students_subject ( id int auto_increment primary key,
subject_name varchar(250) default 'unknown' NOT NULL,
subject_faculty int not null,
foreign key(subject_faculty) references faculty(id));
create table marks (id int auto_increment primary key,
student_id int NOT NULL,
subject_id int NOT NULL,
marks int NOT NULL,
date_of_update datetime default now() ON UPDATE NOW(),
foreign key(student_id) references students(id),
foreign key(subject_id) references students_subject(id));
insert into students ( student_name, dob) values
('rob', '2001-03-06'),
('bbb', '2001-09-06'),
('rab', '1991-03-06'),
('root', '2001-03-16') ;
insert into faculty(faculty_name) values
('kaka'),
('dope'),
('kallie'),
('kim');
insert into students_subject (subject_name, subject_faculty) values
('maths', 2),
('physics', 3),
('english', 4),
('biology', 1),
('statistics', 2),
('french', 4),
('economics',3);
insert into marks ( student_id, subject_id, marks) values
(1,1,70),
(1,2,60),
(1,3,98),
(1,4,75),
(1,5,90),
(1,6,30),
(1,7,40),
(2,1,70),
(2,2,60),
(2,3,70),
(2,4,105),
(2,5,95),
(2,6,30),
(2,7,10),
(3,1,70),
(3,2,60),
(3,3,70),
(3,4,75),
(3,5,99),
(3,6,30),
(3,7,10),
(4,1,70),
(4,2,60),
(4,3,70),
(4,4,89),
(4,5,99),
(4,6,30),
(4,7,19);
I had written Query myself to work out on this but cannot break it though.
select students.id, table_high.marks, table_high.faculty_name as high_faculty, table_high.subject_name as sub_high,
student_low.marks , student_low.faculty_name as faculty_low, student_low.subject_name as sub_low from students
inner join
(select students.id, students.student_name ,marks.marks, subject_joined.faculty_name, students_subject.subject_name from marks
inner join (select students_subject.id,students_subject.subject_name, faculty.faculty_name, students_subject.subject_faculty
from students_subject left join faculty on students_subject.subject_faculty = faculty.id)
as subject_joined on subject_joined.id = marks.subject_id
inner join faculty on subject_joined.subject_faculty = faculty.id
inner join students_subject on students_subject.id = marks.subject_id
inner join students on students.id = marks.student_id
order by 1, 3 desc) as table_high on table_high.id = students.id
inner join
(select students.id, students.student_name ,marks.marks, subject_joined.faculty_name, students_subject.subject_name from marks
inner join (select students_subject.id,students_subject.subject_name, faculty.faculty_name, students_subject.subject_faculty
from students_subject left join faculty on students_subject.subject_faculty = faculty.id)
as subject_joined on subject_joined.id = marks.subject_id
inner join faculty on subject_joined.subject_faculty = faculty.id
inner join students_subject on students_subject.id = marks.subject_id
inner join students on students.id = marks.student_id
order by 1, 3 ) as student_low on student_low.id = students.id
group by 1 ;
attaching screen of output :
Finally resolved this question!
The basic tweak that was required in summarizing this table is that the sub-table had to be joined with a combination of two columns as group by command just reflects the first row value in the summarized table for non-summarized cols, so reflecting values of max and min was not possible at the same time, to which I created sub tables filtering rows through double column joins and finally joined the table to the main student table.
The main table which was joined is Students.
Sub-Table 1 - hw (which summarized the data for highest)
sub-table 1.2 - high for highest marks tagging.
sub-table 2 - lw ( which summarized the table for the lowest)
sub-table 2.1 - low for minimum marks tagging.
Query >>
select students.id, students.student_name, lw.min_marks, lw.lower_subject, lw.lower_faculty,
hw.high_marks, hw.subject_name as high_subject, hw.faculty_name as higher_faculty
from students inner join
(select high.student_id, high.high_marks, high.subject_id, high.subject_name, high.faculty_name
from
(select marks.student_id, marks.marks as high_marks, sub_with_faculty.subject_id, sub_with_faculty.subject_name,
sub_with_faculty.faculty_name from marks
left join
(select students_subject.id as subject_id, students_subject.subject_name, faculty.faculty_name
from students_subject
left join faculty on students_subject.subject_faculty = faculty.id) as sub_with_faculty
on sub_with_faculty.subject_id = marks.subject_id) as high
inner join (select marks.student_id, max(marks) as marks from marks group by 1) as maximum on
maximum.student_id = high.student_id and maximum.marks = high.high_marks) as hw on
hw.student_id = students.id
inner join
(select low.student_id, low.low_marks as min_marks, low.subject_id as lower_subjectID, low.subject_name as lower_subject, low.faculty_name as lower_faculty
from
(select marks.student_id, marks.marks as low_marks, sub_with_faculty.subject_id, sub_with_faculty.subject_name,
sub_with_faculty.faculty_name from marks
left join
(select students_subject.id as subject_id, students_subject.subject_name, faculty.faculty_name
from students_subject
left join faculty on students_subject.subject_faculty = faculty.id) as sub_with_faculty
on sub_with_faculty.subject_id = marks.subject_id) as low
inner join (select marks.student_id, min(marks) as marks from marks group by 1) as minimum on
minimum.student_id = low.student_id and minimum.marks = low.low_marks) as lw on
lw.student_id = students.id;
This could be a good exercise for someone who's new to MySQL like me.
I have a two table called PaymentMaster and PaymentDetails and two table joined by receiptID column. This is my query
SELECT pm.receiptID
, pm.recievedAmount
, pd.invono
, pd.paidAmount
FROM PaymentMaster pm
LEFT JOIN PaymentDetail pd ON pd.receiptID = pm.receiptID
following query provide me this result
note that there are two records in PaymentDetails regarding receiptID PAY0002. That is why two records show for PAY0002. (INV0001,INV0002).
the issue is, I do not want to print PAY0002 in two rows. if the id is same then the column should be empty.The end result should be like this
You can use GROUP BY keyword for grouping them, your query will become something like this
SELECT pm.receiptID
, pm.recievedAmount
, pd.invono
, pd.paidAmount
FROM PaymentMaster pm LEFT JOIN PaymentDetail pd ON pd.receiptID = pm.receiptID GROUP BY pd.receiptID
You could use a variable to control what you display
drop table if exists pm,pd;
create table pm(id varchar(8), amt int);
create table pd(id varchar(8), amt int);
insert into pm values ('aaa',1000),('bbb','100');
insert into pd values ('aaa',100),('aaa',100),('bbb',100);
Select case when rn = 1 then pmid else '' end as pmid,
case when rn = 1 then pmamt else '' end as pmamt,
pdid,pdamt
from
(
select pm.id pmid,pm.amt pmamt,
pd.id pdid, pd.amt pdamt
,if(pm.id<> #p, #rn:=1,#rn:=#rn+1) rn
,#p:=pm.id
from pm
join pd on pd.id = pm.id
,(select #rn:=0,#p:=0) rn
) s
list employees names (Ename) who have both 49008 zip code customers and 49009 zip code customers.
I am struggling to answer the above query based on the above tables.
If the names match between tables assume constraint.
I can filter down to name and zip easily by left joins and group by but struggle after that, I don't know the proper where or having statement. I am assuming it could be done better by a sub query but not sure. Ideally, a single query.
Please and thank you.
1) Create and insert statements for example data:
Create table Employees (EM_Eno INT NOT NULL, EM_Ename VARCHAR(50), EM_Hire_Date DATE, PRIMARY KEY(EM_Eno));
Create table Customers (Customers_Cno INT NOT NULL, Customers_Cname VARCHAR(50), Customers_Street VARCHAR(50), Customers_Zip INT, Customers_Phone INT, primary key(Customers_Cno));
Create table Orders (Orders_Ono INT NOT NULL, Orders_Cno INT, Orders_Eno INT, Orders_Received DATE, Orders_Shipped DATE, primary key(Orders_Ono));
insert into Orders values
( 1,301,501,20161010,20161011);
( 2,302,501,20161011,20161012);
( 3,303,502,20161110,20161111);
( 4,304,502,20161110,20161112);
( 5,305,502,20161110,20161113);
( 6,306,503,20161112,20161114);
( 7,307,501,20161112,20161113);
( 8,308,503,20161112,20161115);
( 9,309,503,20161115,20161120);
(10,300,501,20161112,20161113);
insert into Customers values
(300,'Bryan','100 street',49009,1234567890),
(301,'Ryan','101 street',49008,1234567890),
(302,'Nick','102 street',49009,1234567890),
(303,'Nicholas','103 street',49009,1234567890),
(304,'Alexa','104 street',49009,1234567890),
(305,'Tori','105 street',49008,1234567890),
(306,'Scarlet','106 street',49008,1234567890),
(307,'Heather','100 street',49009,1234567890),
(308,'Amanda','107 street',49008,1234567890),
(309,'James','108 street',49008,1234567890);
insert into Employees values
(501,'Robert',20041010),
(502,'Sam',20050110),
(503,'Brandy',20050710);
2) Ideal end result is answering the query "list employees (names) who have both 49008-zipcode customers and 49009-zipcode customers."
3) Best Attempt thus far:
select Employees.EM_Ename
, Customers.Customers_Zip
from Employees
left
join Orders
on Employees.EM_Eno = Orders.Orders_Eno
left
join Customers
on Orders.Orders_Cno = Customers.Customers_Cno
group
by Employees.EM_Ename
, Customers.Customers_Zip;
The table names are altered slightly in the rextest, because other tables already exist there with the same name...
SELECT e.*
FROM tbl_employees e
JOIN tbl_orders o
ON o.orders_eno = e.em_eno
JOIN tbl_customers c
ON c.Customers_Cno = o.Orders_Cno
WHERE c.Customers_Zip IN(49008,49009)
GROUP
BY e.em_eno
HAVING COUNT(DISTINCT customers_zip) = 2;
http://rextester.com/HCNLU51847
This should be what you want:
select Min(e.Ename)
from #Employees e
join #Orders o on o.Eno = e.Eno
join #Customers c on c.Cno = o.Cno
join #Orders o2 on o2.Eno = e.Eno
join #Customers c2 on c2.Cno = o2.Cno
where o.Ono !=o2.Ono--c.Cno != c2.Cno and
and c.Zip = 49008 and c2.Zip = 49009
group by e.Ename,c.Zip
order by e.Ename
As you can see if you wanted more than those two the self joins become longer.