Left outer join MYSQL returning duplicate rows - mysql

I have this MYSQL Query:
select
sc.supplier,
sq.query_value,
sc.cnv_name as name,
sc.cnv_id,
sq.query_type_id,
qt.query_type_desc,
date_format(sq.query_date, '%d/%m/%Y') as query_date,
qs.query_status,
sq.sla_count,
sq.sla_state,
sq.assigned_to,
IfNull(teams.team_count, 0) team_count,
if(
sq.sla_state is null
OR sq.sla_state = '',
'',
if(
sq.sla_state = 0,
'Query Handler',
if(
sq.sla_state = 1,
'Team Leader',
if(
sq.sla_state = 2,
'Manager',
if(
sq.sla_state = 3,
'Senior Manager',
'Senior Manager (GSCOP BREACH)'
)
)
)
)
) as sla_state_desc,
if(
team_count <= 0
OR team_count is null,
'',
if(team_count > 1, '(multiple)', pt.team_desc)
) as team
from
supconversation sc
left outer join supconvers_querydtls sq on sq.cnv_id = sc.cnv_id
left outer join querytype qt on qt.query_type_id = sq.query_type_id
left outer join querystatus qs on qs.query_status_id = sq.query_status_id
left outer join (
select
count(*) team_count,
tu.user_id
from
teamusers tu,
supconvers_querydtls sq2
where
tu.user_id = sq2.assigned_to
) teams on (teams.user_id = sq.assigned_to)
left outer join teamusers tu on tu.user_id = sq.assigned_to
left outer join portalteam pt on pt.team_id = tu.team_id
where
sc.supplier = 'SUPTEST1'
and sc.cnv_type = 'Q'
order by
query_date desc
What I am trying to do is check if a user has a record in teamusers. The user can be a part of more than 1 team. This is stored in the teamusers table with the columns team_id, user_id. If a user has more than 1 record in teamusers then return team value as (multiple). Otherwise, return the team_desc found in the portalteam table. The portalteam table consists of the columns team_id,team_desc.
This query seems to work but it's returning duplicate rows. I imagine this is because there are multiple records for some users in teamusers. How would I go about fixing this issue?

If you really get duplicated rows then you could try using a select DISTINCT
select distinct
sc.supplier,
sq.query_value,
sc.cnv_name as name,
sc.cnv_id,
sq.query_type_id,
qt.query_type_desc,
date_format(sq.query_date, '%d/%m/%Y') as query_date,
qs.query_status,
sq.sla_count,
sq.sla_state,
sq.assigned_to,
IfNull(teams.team_count, 0) team_count,
if(
sq.sla_state is null
OR sq.sla_state = '',
'',
if(
sq.sla_state = 0,
'Query Handler',
if(
sq.sla_state = 1,
'Team Leader',
if(
sq.sla_state = 2,
'Manager',
if(
sq.sla_state = 3,
'Senior Manager',
'Senior Manager (GSCOP BREACH)'
)
)
)
)
) as sla_state_desc,
if(
team_count <= 0
OR team_count is null,
'',
if(team_count > 1, '(multiple)', pt.team_desc)
) as team
from
supconversation sc
.....
.....

Related

How can I optimize my query it is taking too much time in mysql

Here I'm fetching data using mysql queries but it is taking time around 10 seconds 20 seconds so on ,even though all the columns are indexed. so I'm new to the optimization so please help me
SELECT a.cname,
(SELECT status_name
FROM persontype_status
WHERE status = a.p3_status
LIMIT 1) AS
company_status_psp3,
a.curl,
a.cid,
a.pid,
a.addedbyuser,
a.no_of_emp,
( CASE
WHEN a.lead_status > 0
AND ( a.status = 0
OR a.status > 0 ) THEN (SELECT ( Max(Date(dateadded)) )
FROM d3_info
WHERE cid = a.cid
GROUP BY cid)
WHEN ( a.status > 0
AND a.lead_status = 0 ) THEN (SELECT ( Min(Date(dateadded)) )
FROM sperson_info
WHERE cid = a.cid
GROUP BY cid)
ELSE 0
end ) AS date_new,
a.rank,
a.lead_status,
a.status,
a.magid,
(SELECT pname
FROM personinfo
WHERE pid = a.pid) AS pname,
p1_status,
Count(c.email_id) AS total_mail,
Count(IF(s.mail_type IN( 'First Mail', 'Reminder 1' )
AND c.person_type = 'P1'
AND d.send_status = 1, c.email_id, NULL)) AS t_p1,
Count(IF(s.mail_type IN( 'First Mail', 'Reminder 1' )
AND c.person_type = 'P2'
AND d.send_status = 1, c.email_id, NULL)) AS t_p2,
Count(IF(( s.mail_type IN( 'First Mail', 'Reminder 1' )
AND c.person_type = 'P3'
AND d.send_status = 1 ), c.email_id, NULL)) AS t_p3,
Count(DISTINCT IF(c.person_type = 'P3'
AND c.email_id != '', c.email_id, NULL)) AS t_p3_e,
Count(IF(( s.mail_type IN( 'First Mail', 'Reminder 1' )
AND c.person_type = 'P4'
AND d.send_status = 1 ), c.email_id, NULL)) AS t_p4,
Count(DISTINCT IF(c.person_type = 'P4'
AND c.email_id != '', c.email_id, NULL)) AS t_p4_e,
Count(IF(( s.mail_type IN( 'First Mail', 'Reminder 1' )
AND c.person_type = 'P5'
AND d.send_status = 1 ), c.email_id, NULL)) AS t_p5,
Count(DISTINCT IF(c.person_type = 'P5'
AND c.email_id != '', c.email_id, NULL)) AS t_p5_e,
Count(IF(( s.mail_type IN( 'First Mail', 'Reminder 1' )
AND c.person_type = 'P6'
AND d.send_status = 1 ), c.email_id, NULL)) AS t_p6,
Count(DISTINCT IF(c.person_type = 'P6'
AND c.email_id != '', c.email_id, NULL)) AS t_p6_e,
Count(IF(( s.mail_type IN( 'First Mail', 'Reminder 1' )
AND c.person_type = 'P7'
AND d.send_status = 1 ), c.email_id, NULL)) AS t_p7,
Count(DISTINCT IF(c.person_type = 'P7'
AND c.email_id != '', c.email_id, NULL)) AS t_p7_e,
Count(IF(( s.mail_type IN( 'First Mail', 'Reminder 1' )
AND c.person_type = 'P8'
AND d.send_status = 1 ), c.email_id, NULL)) AS t_p8,
Count(DISTINCT IF(c.person_type = 'P8'
AND c.email_id != '', c.email_id, NULL)) AS t_p8_e FROM mperson_companies a
INNER JOIN aperson_detail c
ON a.cid = c.cid
AND a.pid = c.pid
LEFT JOIN compose d
ON c.email_id = d.receiver_email
AND c.pid = d.pid
LEFT JOIN session_person s
ON d.session_id = s.session_id WHERE a.lead_status = 0
AND a.flag != 'q'
AND a.approval != 5
AND a.pid = 2832
AND a.rank > 1
AND c.email_id != '' GROUP BY a.cid HAVING t_p1 = 2
AND t_p2 = 2
AND IF(t_p3_e = 1, t_p3 = 2, 1 = 1)
AND IF(t_p4_e = 1, t_p4 = 2, 1 = 1)
AND IF(t_p5_e = 1, t_p5 = 2, 1 = 1)
AND IF(t_p6_e = 1, t_p6 = 2, 1 = 1)
AND IF(t_p7_e = 1, t_p7 = 2, 1 = 1)
AND IF(t_p8_e = 1, t_p8 = 2, 1 = 1) ORDER BY date_new DESC;
Need to see SHOW CREATE TABLE and EXPLAIN SELECT.
Meanwhile, this
WHERE a.lead_status = 0
AND a.flag != 'q'
AND a.approval != 5
AND a.pid = 2832
AND a.rank > 1
AND c.email_id != ''
begs for
INDEX(lead_status, pid, -- in either order
flag, approval, -- in either order
rank) -- last
and this
SELECT ( Min(Date(dateadded)) )
FROM sperson_info
WHERE cid = a.cid
GROUP BY cid)
does not need to include GROUP BY cid, since it will return only the one item.
And
( a.status = 0 OR a.status > 0 )
can be simply
a.status >= 0
But, what values are there for status? Inequalities are sometimes less efficient than equalities.
And this
Count(IF(s.mail_type IN( 'First Mail', 'Reminder 1' )
AND c.person_type = 'P2'
AND d.send_status = 1, c.email_id, NULL)
)
can be shortened to
SUM( s.mail_type IN( 'First Mail', 'Reminder 1' )
AND c.person_type = 'P2'
AND d.send_status = 1 )
There may be more suggestions; this could take a few iterations.

optimize my query mysql - PHP

I have this query that takes more than 10 seconds,
The most bulky table is requetes, the clause where depends on filter:
SELECT SQL_CALC_FOUND_ROWS
requetes.id AS thread_id,
requetes.id AS thread_id2,
CONCAT_WS("/", SUBSTR(requetes.id, 5, 2), SUBSTR(requetes.id, 3, 2), SUBSTR(requetes.id, 1, 2)) AS thread_create_date,
DATE_FORMAT(create_date, "%d/%m/%Y %H:%i") AS create_date,
IF(UNIX_TIMESTAMP(requetes.date_objectif_requete) = 0, NULL, DATE_FORMAT(requetes.date_objectif_requete, "%d/%m/%Y %H:%i:%S")) AS thread_target_date,
IF(UNIX_TIMESTAMP(requetes.date_objectif_requete) = 0, NULL, DATE_FORMAT(requetes.date_objectif_requete, "%Y%m%d")) AS int_thread_target_date,
requetes.prenom AS customer_first_name,
requetes.nom AS customer_last_name,
requetes.subject AS subject_action,
requetes.ident_e AS code_customer,
CONCAT_WS(" ", UPPER(requetes.nom), requetes.prenom, requetes.pseudo) AS complete_customer_name,
requetes.type_rs AS type_rs,
themes_sous.id AS thread_type_id,
requetes.cp AS zip_code,
requetes.libelle_pc_origine AS libelle_pc_origine,
themes_sous.libelle AS thread_type_label,
themes_sous.action_page AS thread_type_target_url,
agents.prenom AS user_first_name,
agents.nom AS user_last_name,
req_agent.id_agent AS code_user,
CONCAT_WS(" ", UPPER(agents.nom), agents.prenom) AS complete_user_name,
(1 - statut_inverse) AS done,
archive AS archived,
num_messages,
themes.libelle AS libelle_categ
FROM requetes
LEFT OUTER JOIN themes_sous
ON requetes.id_ss_theme = themes_sous.id
LEFT OUTER JOIN req_agent
ON requetes.id = req_agent.id_requete
LEFT OUTER JOIN agents
ON req_agent.id_agent = agents.id
LEFT OUTER JOIN themes
ON themes.id = themes_sous.id_theme
WHERE requetes.client_identifier=4
AND themes_sous.client_identifier=4
AND requetes.statut_inverse = 1 AND DATE_FORMAT(requetes.date_objectif_requete, "%Y%m%d") <> 20171215 AND NOT (DATE_FORMAT(requetes.date_objectif_requete, "%Y%m%d") > 20171215) AND ( req_agent.id_agent_origine = "5087050" ) AND requetes.date_objectif_requete IS NOT NULL AND requetes.date_objectif_requete <> "0000-00-00 00:00:00"
ORDER BY requetes.id LIMIT 0, 25;
The explain of this query is :
explain of the query
config of the most bulky table
thanks for your help

MySQL Multiple Case When Exists Statement

I have two tables. Let's call it: SEATS and SEAT_ALLOCATION_RULE table.
Below are the table schema:
CREATE TABLE IF NOT EXISTS `SEATS` (
`SeatID` int(11) NOT NULL AUTO_INCREMENT,
`SeatName` varchar(255) NOT NULL DEFAULT '',
PRIMARY KEY (`SeatID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=9 ;
INSERT INTO `SEATS` (`SeatID`, `SeatName`) VALUES
(1, 'Super VIP'),
(2, 'VIP'),
(3, 'Business'),
(4, 'Economy'),
(5, 'Standing');
CREATE TABLE IF NOT EXISTS `SEAT_ALLOCATION_RULE` (
`SeatID` int(11) NOT NULL DEFAULT '0',
`Origin` varchar(50) NOT NULL DEFAULT '0',
`Destination` varchar(50) NOT NULL DEFAULT '',
`Passenger_Type` varchar(25) NOT NULL DEFAULT '',
PRIMARY KEY (`SeatID`,`Origin`,`Destination`,`Passenger_Type`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO `SEAT_ALLOCATION_RULE` (`SeatID`, `Origin`, `Destination, `Passenger_Type`) VALUES
(1, 'Malaysia','',''),
(2, 'Malaysia','Singapore',''),
(3, 'Malaysia','Singapore','Senior_Citizen'),
(4, 'Bangkok','Japan','Student'),
(5, 'Cambodia','China','Senior_Citizen');
SEAT_ALLOCATION_RULE table determines which seat should a passenger be assigned to based on the following order in priority:
1. Origin, destination, and passenger_type match
2. Origin and destination match
3. Origin match
It means that if all the fields (origin, destination, and passenger_type) match, it should take higher priority than if it is just two fields match and so on. If a column is empty, it is considered as unspecified and hence has lower priority. So, for example:
If the Origin is Malaysia, Destination is Singapore, and Passenger_Type is Senior_Citizen, it should return seatID 3
If the Origin is Malaysia, Destination is Singapore, and Passenger_Type is Student, it should return seatID 2 (since it only match Origin and Destination)
If the Origin is Malaysia, Destination is US, and Passenger_Type is Student, it should return seatID 1 (since it only match Origin).
Now, based on the rules above, if the origin is Malaysia, destination is Singapore, and Passenger_Type is student, the query to return seatID is as follow:
SELECT s.SeatID, s.SeatName
FROM SEATS s
WHERE
CASE WHEN EXISTS(
select 1
from SEAT_ALLOCATION_RULE r
where s.SeatID = r.SeatID
AND r.Origin = 'Malaysia'
AND r.Destination = 'Singapore'
AND r.Passenger_Type='Student') Then 1
WHEN EXISTS(
select 1
from SEAT_ALLOCATION_RULE r
where s.SeatID = r.SeatID
AND r.Origin = 'Malaysia'
AND r.Destination = 'Singapore'
AND r.Passenger_Type='') Then 1
WHEN EXISTS(
select 1
from SEAT_ALLOCATION_RULE r
where s.SeatID = r.SeatID
AND r.Origin = 'Malaysia'
AND r.Destination = ''
AND r.Passenger_Type='') Then 1 END
However, the query above does not work as it will return seatID 1 and 2, but the expected output is only seatID 2 (since origin and destination matches and it takes higher precedence). Can someone help to correct my SQL query?
This should do the trick:
select seatid
from seat_allocation_rule sar
order by ((sar.origin = :origin) << 2) + ((sar.destination = :destination) << 1) + (sar.passenger_type = :passenger_type) desc,
((sar.origin <> '') << 2) + ((sar.destination <> '') << 1) + (sar.passenger_type <> '') asc
limit 1
To understand how:
create table testcase (
origin varchar(255),
destination varchar(255),
passenger_type varchar(255),
expected_seat int(11)
);
insert into testcase values ('Malaysia','Singapore','Senior_Citizen',3),
('Malaysia','Singapore','Student',2),
('Malaysia','US','Student',1);
select * from (
select tc.*,
sar.seatid,
case when sar.seatid = tc.expected_seat then 'Y' else '-' end as pass,
((sar.origin = tc.origin) << 2)
+ ((sar.destination = tc.destination) << 1)
+ ((sar.passenger_type = tc.passenger_type) << 0) as score,
((sar.origin <> '') << 2)
+ ((sar.destination <> '') << 1)
+ ((sar.passenger_type <> '') << 0) as priority
from seat_allocation_rule sar
cross join testcase tc
) x order by expected_seat desc, score desc, priority asc;
This fixes the existing SQL:
SELECT DISTINCT s.SeatID, s.SeatName
FROM SEATS s
LEFT JOIN SEAT_ALLOCATION_RULE r ON r.SeatID = s.SeatID
AND r.Origin = 'Malaysia'
AND (
(r.Destination = 'Singapore' AND r.Passenger_Type IN ('Student', ''))
OR
(r.Destination = '' AND r.Passenger_Type = '')
)
WHERE r.SeatID IS NOT NULL
But it's only a partial solution, and it's hand-coding logic you really want to apply based solely on the data.
A complete solution will use hypothetical inputs for your passenger's ticket info to produce all eligible seats. This is a great use of lateral joins/apply, which are sadly lacking in MySql (all of their major competitors have had these for at least two release cycles, along with other gems that are absent from the current MySql release like windowing functions, ctes, full joins... I could go on). Here's how I'd do it in Sql Server:
SELECT p.PassengerID, s.SeatID, s.SeatName
FROM Passenger p
CROSS APPLY (
SELECT TOP 1 r.SeatID
FROM SEAT_ALLOCATION_RULE r
WHERE COALESCE(NULLIF(r.Origin, ''),p.Origin) = p.Origin
AND COALESCE(NULLIF(r.Destination,''), p.Destination) = p.Destination
AND COALESCE(NULLIF(r.Passenger_Type,''),p.Passenger_Type) = p.Passenger_Type
ORDER BY
CASE WHEN r.Origin <> '' THEN 1 ELSE 0 END
+ CASE WHEN r.Destination <> '' THEN 1 ELSE 0 END
+ CASE WHEN r.Passenger_Type <> '' THEN 1 ELSE 0 END DESC
) r
INNER JOIN SEATS s ON s.SeatID = r.SeatID
WHERE p.PassengerID = /* passenger criteria here */
I know the Sql Server solution isn't much immediate help to you, but perhaps it will suggest a better MySql solution.
Without APPLY, the only way I know to do this is to first compute the MAX() match count for your passengers (how many parts of the rules match):
SELECT p.PassengerID,
MAX(CASE WHEN r.Origin <> '' THEN 1 ELSE 0 END
+ CASE WHEN r.Destination <> '' THEN 1 ELSE 0 END
+ CASE WHEN r.Passenger_Type <> '' THEN 1 ELSE 0 END) AS MatchCount
FROM Passenger p
INNER JOIN SEAT_ALLOCATION_RULE r ON COALESCE(NULLIF(r.Origin, ''),p.Origin) = p.Origin
AND COALESCE(NULLIF(r.Destination,''), p.Destination) = p.Destination
AND COALESCE(NULLIF(r.Passenger_Type,''),p.Passenger_Type) = p.Passenger_Type
GROUP BY p.PassengerID
And then use that to filter down to results that have the same number of matches:
SELECT p
FROM Passenger p
INNER JOIN ( /* matchecounts */
SELECT p.PassengerID,
MAX(CASE WHEN r.Origin <> '' THEN 1 ELSE 0 END
+ CASE WHEN r.Destination <> '' THEN 1 ELSE 0 END
+ CASE WHEN r.Passenger_Type <> '' THEN 1 ELSE 0 END) AS MatchCount
FROM Passenger p
INNER JOIN SEAT_ALLOCATION_RULE r ON COALESCE(NULLIF(r.Origin, ''),p.Origin) = p.Origin
AND COALESCE(NULLIF(r.Destination,''), p.Destination) = p.Destination
AND COALESCE(NULLIF(r.Passenger_Type,''),p.Passenger_Type) = p.Passenger_Type
GROUP BY p.PassengerID
) m ON m.PassengerID = p.PassengerID
INNER JOIN SEAT_ALLOCATION_RULE r ON COALESCE(NULLIF(r.Origin, ''),p.Origin) = p.Origin
AND COALESCE(NULLIF(r.Destination,''), p.Destination) = p.Destination
AND COALESCE(NULLIF(r.Passenger_Type,''),p.Passenger_Type) = p.Passenger_Type
INNER JOIN SEATS s ON s.SeatID = r.SeatID
WHERE m.MatchCount =
(CASE WHEN r.Origin <> '' THEN 1 ELSE 0 END
+ CASE WHEN r.Destination <> '' THEN 1 ELSE 0 END
+ CASE WHEN r.Passenger_Type <> '' THEN 1 ELSE 0 END)
AND p.PassengerID = /* Passenger criteria here */
Which repeats a lot of code as well as effort in the DB, and is not very efficient. You can repeat the passenger criteria in the nested query, but that would only help a little. This option might also return multiple records for a passenger if they match two rules equally, though you can solve this easily enough with a GROUP BY expression.
In either case, note you can improve performance and simplify code by using actual NULL values instead of empty strings for missing parts of the SEAT_ALLOCATION_RULE table.

How to display result and handle errors # 1242?

I want to:
if the value qty_out! = 0, then set qty_out = 0
Help me to display results
SELECT
SUBSTR(stok_control.tgl_faktur,9,2) AS 'tanggal',
SUBSTR(stok_control.tgl_faktur,6,2) AS 'bulan',
CONCAT(
(SELECT(
IFNULL(stok_control.faktur_beli,''))
)
,
(SELECT(
IFNULL(stok_control.faktur_jual,''))
)
) AS 'faktur',
bahan.id AS 'kode_bahan',
bahan.nm_bahan AS 'nama_bahan',
stok_control.qty_in AS 'masuk',
(
SELECT IF(stok_control.qty_out != '',0,0)
FROM
stok_control
WHERE
stok_control.faktur_beli !=''
) AS 'keluar'
FROM
stok_control
LEFT JOIN bahan ON stok_control.id_bahan=bahan.id
#eggyal, I have changed your code to be:
SELECT
SUBSTR(sc.tgl_faktur, 9, 2) AS 'tanggal',
SUBSTR(sc.tgl_faktur, 6, 2) AS 'bulan',
CONCAT(
IFNULL(sc.faktur_beli, ''),
IFNULL(sc.faktur_jual, '')
) AS 'faktur',
b.id AS 'kode_bahan',
b.nm_bahan AS 'nama_bahan',
(SELECT IFNULL(sc.qty_in,0)) AS 'masuk',
(SELECT
(
IF(faktur_beli <> '',
0,
(SELECT sc.qty_out)
)
)
) AS 'qty_out'
FROM
stok_control sc LEFT JOIN bahan b ON sc.id_bahan = b.id
I've tried to reference an existing but still error...
I want to:
if the value qty_out! = 0, then set qty_out = 0
Do you mean that you want qty_out to be 0 irrespective of its original value?
SELECT SUBSTR(sc.tgl_faktur, 9, 2) AS tanggal,
SUBSTR(sc.tgl_faktur, 6, 2) AS bulan,
CONCAT(
IFNULL(sc.faktur_beli, ''),
IFNULL(sc.faktur_jual, '')
) AS faktur,
b.id AS kode_bahan,
b.nm_bahan AS nama_bahan,
sc.qty_in AS masuk,
0 AS qty_out
FROM stok_control sc LEFT JOIN bahan b ON sc.id_bahan = b.id

SQL Subquery Questions

I am trying to combine these 2 queries in such a way to determine who the PI is that owns equipment (>$100K value). I have the ability to find all the equipment one PI owns that is greater then 100k. I also have the ability to see all the PIs. I just cannot get these 2 queries to combine. I have tried with a WHERE subquery and an EXIST subquery. I want to be able to find all the equipment (matched with its PI owner) where the PI exists in query #2.
Query #1 for finding equipment of a specific PI
select Account_No,Inventory_No,Building_No,Room_No,CDDEPT,Location,Normalized_MFG,Manufacturer_Name,Normalized_Model,Name,Serial_Code,CONCAT( '$', FORMAT( Cost, 2 ) ) as Cost, Equipment_Inventory_Normalized.Active
from Temp_Equipment_Inventory.Equipment_Inventory_Normalized, `paul`.`ROOM`, `paul`.`BLDG`, `paul`.`LABORATORY`, `paul`.`PERSON`
where (`PERSON`.`ID` = `LABORATORY`.`PI_ID` OR `PERSON`.`ID` = `LABORATORY`.`SUPV_ID`)
AND `LABORATORY`.`RM_ID` = `ROOM`.`ID`
AND `LABORATORY`.`ACTIVE` = '1'
AND `ROOM`.`BLDG_ID` = `BLDG`.`ID`
AND ((
`BLDG`.`BLDGNUM` = Equipment_Inventory_Normalized.Building_No
AND Equipment_Inventory_Normalized.Actual_Building IS NULL
AND (`BLDG`.`BLDGNUM` != '1023' AND `LABORATORY`.`OTHER_LEVEL` != '1' AND `ROOM`.`RMNUM` != '0199')
)OR (
`BLDG`.`BLDGNUM` = Equipment_Inventory_Normalized.Actual_Building AND
(`BLDG`.`BLDGNUM` != '1023' AND `LABORATORY`.`OTHER_LEVEL` != '1' AND `ROOM`.`RMNUM` != '0199')
))
AND ((
`ROOM`.`RMNUM` = Equipment_Inventory_Normalized.Room_No
AND Equipment_Inventory_Normalized.Actual_Room IS NULL
)OR (
`ROOM`.`RMNUM` = Equipment_Inventory_Normalized.Actual_Room
))
AND Equipment_Inventory_Normalized.Active !=0
AND SurplusPending != '1'
AND Cost >= 100000
AND `PERSON`.`CANNUM`='810010787'
Query 2 that finds all the PIs
select distinct i.CAN
from CGWarehouse.CCGV10WC w
inner join CGWarehouse.CCGV10IC i
on w.PROJECT_NUMBER=i.SPONSORED_PROJECT
and w.SEQUENCE_NUMBER=i.PROJECT_SEQUENCE
where w.STATUS='A'
and i.PRIN_INVEST_CODE='Y'
and i.DEL_CODE!='Y'
and i.CAN IS NOT NULL
Perhaps you're looking for the IN keyword in your WHERE clause?
Forgive me, but I had to clean up the formatting of your query a little...it's kinda my OCD thing:
SELECT
Account_No,
Inventory_No,
Building_No,
Room_No,
CDDEPT,
Location,
Normalized_MFG,
Manufacturer_Name,
Normalized_Model,
Name,
Serial_Code,
CONCAT('$', FORMAT( Cost, 2 )) AS Cost,
Equipment_Inventory_Normalized.Active
FROM
Temp_Equipment_Inventory.Equipment_Inventory_Normalized a,
`paul`.`ROOM`,
`paul`.`BLDG`,
`paul`.`LABORATORY`,
`paul`.`PERSON`
WHERE
(`PERSON`.`ID` = `LABORATORY`.`PI_ID` OR `PERSON`.`ID` = `LABORATORY`.`SUPV_ID`)
AND `LABORATORY`.`RM_ID` = `ROOM`.`ID`
AND `LABORATORY`.`ACTIVE` = '1'
AND `ROOM`.`BLDG_ID` = `BLDG`.`ID`
AND (
(
`BLDG`.`BLDGNUM` = Equipment_Inventory_Normalized.Building_No
AND Equipment_Inventory_Normalized.Actual_Building IS NULL
AND `BLDG`.`BLDGNUM` != '1023'
AND `LABORATORY`.`OTHER_LEVEL` != '1'
AND `ROOM`.`RMNUM` != '0199'
) OR (
`BLDG`.`BLDGNUM` = Equipment_Inventory_Normalized.Actual_Building
AND `BLDG`.`BLDGNUM` != '1023'
AND `LABORATORY`.`OTHER_LEVEL` != '1'
AND `ROOM`.`RMNUM` != '0199'
)
)
AND (
(
`ROOM`.`RMNUM` = Equipment_Inventory_Normalized.Room_No
AND Equipment_Inventory_Normalized.Actual_Room IS NULL
) OR (
`ROOM`.`RMNUM` = Equipment_Inventory_Normalized.Actual_Room
)
)
AND Equipment_Inventory_Normalized.Active !=0
AND SurplusPending != '1'
AND Cost >= 100000
AND `PERSON`.`CANNUM` IN ( /* this assumes that the `PERSON`.`CANNUM` column matches up with the CGWarehouse.CCGV10IC.CAN column */
SELECT DISTINCT i.CAN
FROM
CGWarehouse.CCGV10WC w
INNER JOIN CGWarehouse.CCGV10IC i ON w.PROJECT_NUMBER=i.SPONSORED_PROJECT AND w.SEQUENCE_NUMBER=i.PROJECT_SEQUENCE
WHERE
w.STATUS='A'
AND i.PRIN_INVEST_CODE='Y'
AND i.DEL_CODE!='Y'
AND i.CAN IS NOT NULL
)