Advanced MySQL Joining. Speeding up query

后端 未结 3 766
春和景丽
春和景丽 2021-01-23 01:56

I have a list of users on my php application (using codeigniter). Each user may have completed a form with about 1000 or so total fields. The structure looks similar to this:

3条回答
  •  后悔当初
    2021-01-23 02:40

    There is a way but it gets over expensive the more you add fields. The same thing occurs with many CMS that choose to store additionnal user data in that form.

    You can get a working search SQL using this:

    SELECT
        users.*,
        firstname.data AS firstname,
        lastname.data AS lastname,
        eyecolor.data AS eyecolor,
    
    FROM
        users
        LEFT JOIN completed_form_fields AS firstname ON firstname.userid = users.id AND firstname.fieldkey = "firstname"
        LEFT JOIN completed_form_fields AS lastname ON lastname.userid = users.id AND lastname.fieldkey = "lastname"
        LEFT JOIN completed_form_fields AS eyecolor ON eyecolor.userid = users.id AND eyecolor.fieldkey = "eyecolor"
    
    WHERE
        firstname.data LIKE '%searchdata%'
        OR lastname.data LIKE '%searchdata%'
        OR eyecolor.data LIKE '%searchdata%'
    

    This method gets very big and expensive for the MySQL server the more you add tables. Therefore, i would recommend not to go more than 10-15 joins like that and then again, i'd profile it to make sure.

提交回复
热议问题