I have a MySQL table with a large amount of records (~20k), which is in 1NF. Unfortunately converting it to 2NF and above is not an option here.
The Table contains data such as
ClientName1 | ClientLastName1 | ClientZip1 | ... | Product1
ClientName1 | ClientLastName1 | ClientZip1 | ... | Product2
ClientName1 | ClientLastName1 | ClientZip1 | ... | Product3
ClientName2 | ClientLastName2 | ClientZip2 | ... | ProductX
ClientName3 | ClientLastName3 | ClientZip3 | ... | Product1
ClientName3 | ClientLastName3 | ClientZip3 | ... | Product2
ClientName4 | ClientLastName4 | ClientZip4 | ... | Product2
ClientName4 | ClientLastName4 | ClientZip4 | ... | Product3
What i would like to do is to get all the products of a client who has at least Product1.
So in the example above that would be the following records:
ClientName1 | ClientLastName1 | ClientZip1 | ... | Product1
ClientName1 | ClientLastName1 | ClientZip1 | ... | Product2
ClientName1 | ClientLastName1 | ClientZip1 | ... | Product3
ClientName3 | ClientLastName3 | ClientZip3 | ... | Product1
ClientName3 | ClientLastName3 | ClientZip3 | ... | Product2
For now lets assume (ClientName,ClientLastname) are unique for each client.
I used the following query assuming the the Table Name is clients
SELECT
ClientID
FROM
clients cl
WHERE (ClientName,ClientLastname)
IN (
SELECT ClientName, ClientLastname
FROM clients
GROUP BY ClientName,ClientLastname,Product
HAVING Product IN (Product1ID)
)
First of all this query runs for ages, and seems not to terminate (or at least not in a reasonable time) and second of all i think it is not correct.
In an ideal world, my suggestion would be to try to normalize this table, as much as possible. As you can see, you have a mess of a table to try to work with.
But have you tried something like this (See SQL Fiddle with Demo):