• Welcome to TechPowerUp Forums, Guest! Please check out our forum guidelines for info related to our community.

MySql SELECT statement help please

Aquinus

Resident Wat-man
Joined
Jan 28, 2012
Messages
13,147 (2.94/day)
Location
Concord, NH, USA
System Name Apollo
Processor Intel Core i9 9880H
Motherboard Some proprietary Apple thing.
Memory 64GB DDR4-2667
Video Card(s) AMD Radeon Pro 5600M, 8GB HBM2
Storage 1TB Apple NVMe, 4TB External
Display(s) Laptop @ 3072x1920 + 2x LG 5k Ultrafine TB3 displays
Case MacBook Pro (16", 2019)
Audio Device(s) AirPods Pro, Sennheiser HD 380s w/ FIIO Alpen 2, or Logitech 2.1 Speakers
Power Supply 96w Power Adapter
Mouse Logitech MX Master 3
Keyboard Logitech G915, GL Clicky
Software MacOS 12.1
I would use the LEFT JOIN version that Biggie wrote 2 posts ago. Sub-queries can have performance penalties if there are enough nested loops generated by the query planner. It's been quite some time since I've used MySQL but PostgreSQL will let you add "EXPLAIN ANALYZE" to the beginning of any SELECT query and it will describe how the query planning is going to attack doing the query.

Without seeing anything like that, it looks like that an index on staff_cpd.staffid and an index on staff_cpd.cpdid (if not already a primary key) might speed up the query.

Also next time you ask a SQL question, try to include some schema so we know what we're querying.
 
Joined
Oct 24, 2009
Messages
430 (0.08/day)
Location
Belgium
System Name Illidan
Processor AMD Ryzen 9 5900X
Motherboard Gigabyte B550 Aorus Pro V2
Cooling Scythe Mugen 4
Memory G.Skill Trident Z 32GB DDR4 3000MHz 14CL
Video Card(s) AMD Radeon RX 6900 XT
Storage Crucial P1 1TB + Sandisk Ultra II 960GB + Samsung EVO Plus 970 2TB + F3 1TB + Toshiba X300 4TB
Display(s) Iiyama G-MASTER G4380UHSU-B1
Case Corsair 750D Airflow
Audio Device(s) Sony WH1000-XM4
Power Supply Seasonic Focus PX-850
Mouse Logitech G604
Keyboard Corsair Vengeance K70 (Cherry MX Red)
Software Windows 11 Pro
True. For a simple query like this the optimizer would normally see that it's the same subquery over and over again and only execute it once and keep it in memory.
Alas this is not always the case. In Oracle I use the WITH clause for large subqueries and if it gets recalculated for every row, I use the materialize hint to change the explain plan so it would get fetched from the memory. This is of course a bit dirty, but the statistics on the database I work with (+-500GB of raw data) aren't always up to date or completely wrong and sometimes give weird explain plans.
 
Top