I’m usually pretty good at figuring out efficient ways to query my databases, but I’m completely stuck on how to get the info I need without a slow subquery. Hoping someone here can help:
First off, this is running in a mysql database.
I have 2 tables: hardware, and hardware_to_license.
[code]hardware:
id
serial_number
hardware_to_license
id
hardware_id
license_id[/code]
There is also a license table, but that is not needed for this query. These 3 tables tie specific devices (hardware) to specific licenses. A license can have multiple pieces of hardware tied to it, so I have the hardware_to_license tying table.
Here is what I need: Given a serial number, find all the serial numbers of devices attached to the same license.
My subquery approach looks something like this:
select h.serial_number from hardware h, hardware_to_license htl where htl.hardware_id = h.id and htl.license_id in (
select htl2.license_id from hardware h2, hardware_to_license htl2 where h2.serial_number = '123456'
)
The above works, but can be VERY slow, since there are potentially many thousands of devices and many thousands of licenses, with many more thousands of entries in the hardware_to_license table, and the subquery forces a full table scan on every matching row in the hardware_to_license table.
My intuition tells me there is a nasty incestuous type of join I should be able to do here, but none of my sql-fu so far has yielded any correct results. This one appears to be very close, but lists the same serial number 3 times (there are 3 pieces of hardware attached to this specific license:
select h.serial_number from hardware h left join hardware_to_license htl on htl.hardware_id = h.id left join hardware_to_license htl2 on htl.license_id = htl2.license_id where h.serial_number = 'AE3319GC';
If you are still reading… erhm… help?