I have a following table named [clients] with columns and values as follows:
+--------+-----------+--------------+----------------+
| uid | client_id | client_input | input_value |
+--------+-----------+--------------+----------------+
| 1 | 22 | City | Seattle |
+--------+-----------+--------------+----------------+
| 2 | 45 | City | Ojai |
+--------+-----------+--------------+----------------+
| 3 | 22 | State | OR |
+--------+-----------+--------------+----------------+
| 4 | 45 | State | CA |
+--------+-----------+--------------+----------------+
| 5 | 65 | City | Orlando |
+--------+-----------+--------------+----------------+
| 6 | 74 | State | AB |
+--------+-----------+--------------+----------------+
| 7 | 65 | State | FL |
+--------+-----------+--------------+----------------+
| 8 | 12 | City | Los Angeles |
+--------+-----------+--------------+----------------+
| 9 | 12 | State | CA |
I need PHP/MySql query which would list all the cities present in the input_value column which are located in the state of 'CA'. Obviously the common identifier is the client_id which is always a match because if client is in 'Los Angeles' the same client_id is also in the row which contains the value of 'CA' in the input_value column. This table has over 8 million rows and any fast performing equerry is highly appreciated.
My brain fried, deadline approaching, can't change the table design, need help, please!
SELECT *
FROM table AS t1 INNER JOIN table AS t2 ON t1.client_id = t2.client_id
WHERE t1.client_input = 'City' AND t2.client_input = 'State' AND t2.input_value = 'CA'
Note: This may need some adjustments and could likely be optimized. But it should get you started and cool your brain.
I did not tested this query. But this or a similar query should work. I first used two subqueries to avoid unecessary joins. The first subquery filters for the state 'CA' and the second subquery for cities. If you want a table for all cities by their state, remove the 'CA' clause from subquery a.
SELECT b.input_value AS city, a.input_value AS state
FROM
(SELECT client_id, input_value
FROM tablename
WHERE input_value = 'CA'
AND client_input = 'State')
AS a,
(SELECT client_id, input_value
FROM tablename
WHERE client_input = 'City')
AS b
WHERE a.client_id = b.client_id
SELECT distinct
t2.Input_Value as City
from
YourTable t1
JOIN YourTable t2
on t1.client_ID = t2.Client_ID
AND t2.client_input = 'City'
where
t1.client_input = 'State'
AND t1.Input_Value = 'CA'
I would have two indexes... (Client_Input, Input_Value) and (Client_ID, Client_Input, Input_Value)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.