简体   繁体   中英

Getting data from 3 MySQL tables

I'm having a struggle here trying to grab some data from 3 database tables..

The idea is that users can fill out their profile with several fields, and I'm storing every profile field, field values and the users selected value in separate tables.

The structure of the tables look like this:

Table 'profile_fields'
- id
- name
- sort
- status (enum '0', '1')

Table 'profile_field_values'
- id
- profile_field_id
- name

Table 'user_profile_fields'
- user_id
- profile_field_id
- profile_field_value_id

Would be really nice if you could tell me how to construct this query, and why you used the JOIN you did.

Also, how would this table layout scale when the userbase grows?

Thank you so much in advance!

Edit: OK, I still can't figure out how to make it return all the fields from 'profile_fields' along with the users selected option from 'user_profile_fields'. If the user hasn't selected a value, it should just be null.

This is my (non-functional) query so far:

SELECT  PF.id AS field_id, PF.name AS field_name, UPF.profile_field_value_id AS value_id, PF.type, PFV.name 
FROM  profile_fields  PF
LEFT JOIN profile_fields_values PFV ON PFV.profile_field_id = PF.id
LEFT JOIN user_profile_fields UPF ON UPF.user_id=1  AND PF.id = UPF.profile_field_id
WHERE length(PF.name) > 0 and PF.status = '1'
ORDER BY PF.sort

This query seems to work, but it does not fetch the name of the value from 'profile_field_values':

SELECT PF.id AS field_id, PF.name AS field_name, UPF.profile_field_value_id AS value_id, PF.type
FROM profile_fields PF
LEFT JOIN user_profile_fields UPF ON UPF.user_id =1
AND PF.id = UPF.profile_field_id
WHERE LENGTH( PF.name ) >0
AND PF.status =  '1'
ORDER BY PF.sort

I think you have some unnecessary complexity in there. Maybe you should try

Table 'profile_fields'

  • id
  • name
  • sort
  • status (enum '0', '1')

Table 'profile_field_values'

  • id
  • user_id
  • profile_field_id
  • value

why are there 3 tables?

Seems like simple JOINs should work:

SELECT pf.id, pf.name, pf.sort, pf.status,
    pfv.id, pfv.profile_field_id, pfv.name,
    upf.user_id, upf.profile_field_id, upf.profile_field_value_id
FROM profile_fields pf
    INNER JOIN profile_field_values pfv 
        ON pf.id = pfv.profile_field_id
    INNER JOIN user_profile_fields upf 
        ON upf.profile_field_value_id = pfv.id AND upf.profile_field_id = pf.id

A Visual Explanation of SQL Joins

This uses an INNER JOIN to select all matching records from each table -- review the post to tell the difference between an INNER and an OUTER join.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM