1

I have added a custom fields on the user management, which works greats, the custom fields are save on fields fields_values tables, I don't find a way to join the info from user table users table and the fields tables in one query results.

I need something like: SELECT id,NAME,username,customfield FROM users WHERE Id=2

How can I achieve that?

3
  • It's 'achieve'. Try JOIN. Commented Aug 22, 2017 at 7:14
  • Thank you @Strawberry for the spelling correction, you said to join, but I don't see what table to join with in order to get the result I want, don't you? Commented Aug 22, 2017 at 23:30
  • Which value should be extracted from fields_values? This question is a little too incomplete. Commented Jul 19, 2021 at 10:35

2 Answers 2

1
SELECT u.*, field_id as fid, value as fvalue FROM `#__users` as u  LEFT JOIN `#__fields_values` AS f ON u.id = f.item_id WHERE u.id=2

// u as user table
// f as fileds table
// u.id as userid (user table user id)
// f.item_id as userid (fields table user id)
Sign up to request clarification or add additional context in comments.

5 Comments

It would be very helpful to future researchers if you provide your answer using the Joomla query methods.
Do you know how to do this? (I don't mean to be condescending)
am a Joomla Developer for last 5yrs
Great. Well, since the #_ needs Joomla to fill in the prefix and because this is tagged with Joomla, you might be so kind to post how to construct this query using Joomla query building methods.
I have build my project multi tables joining and learning query language, but this query lack in performance. so i need to improve
0

I found this link: https://ubiq.co/database-blog/transpose-rows-columns-dynamically-mysql/ which helped me to create a pure MySQL solution:


SET @sql = NULL;
SELECT
    GROUP_CONCAT(
        'max(case when `f`.`name` = ''',
        `f`.`name`,
        ''' then `fv`.`value` end) `',
        `f`.`name`,
        '`'
    ) INTO @sql
FROM `#__fields` `f` 
JOIN `#__fields_groups` `fg` ON `f`.`group_id`=`fg`.`id`
WHERE `f`.`context`='com_users.user' ORDER BY `fg`.`ordering`,`f`.`ordering`;

SET @sql = CONCAT('SELECT `u`.*, ', @sql, ' 
FROM `#__users` `u`
JOIN `#__fields_values` `fv` ON `u`.`id`=`fv`.`item_id`
JOIN `#__fields` `f` ON `fv`.`field_id`=`f`.`id`
GROUP BY `u`.`id` ORDER BY `u`.`name`');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

Also answered here: https://joomla.stackexchange.com/questions/31797/how-to-join-custom-fields-data-to-users-table-without-extra-rows-in-result-set/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.