I am using join in laravel with mutiples and different conditions but I have a problem the quantity and the date column is always null but when I see in the database the column is not null it has some value it is only null when I am using join.
$contact_packages = Contact::where('contacts.id','!=',1)
->leftJoin('transactions as t','t.id','=','contacts.id')
->leftJoin('transaction_sell_lines as tsl','tsl.transaction_id','=','t.id')
->join('customer_package as cp','contacts.id','=','cp.contact_id')
->join('package as p','cp.package_id','=','p.id')
->join('customer_package_service as cps','cps.customer_package_id','=','cp.id')
->leftJoin('categories as c','p.category_id','=','c.id')
->leftJoin('categories as sc','p.sub_category_id','=','sc.id')
// ->where('cps.customer_package_id','cp.id')
->select([
'contacts.id as cid',
'contacts.name as cname',
'p.id as pid',
'p.name as pname',
DB::raw('TRIM(tsl.quantity)+0 as pqty'),
// 'tsl.quantity as pqty',
DB::raw('count(cps.product_id) as services'),
DB::raw('COUNT(CASE WHEN cps.status = 0 THEN cps.product_id END) as pending'),
DB::raw('COUNT(CASE WHEN cps.status = 1 THEN cps.product_id END) as redeemed'),
't.created_at as date',
'c.name as pc',
'sc.name as psc',
'p.expire_days as ped',
'cps.customer_package_id as cpid'
])
->groupBy('cpid')
->get();
select `contacts`.`id` as `cid`, `contacts`.`name` as `cname`,
`p`.`id` as `pid`, `p`.`name` as `pname`,
TRIM(tsl.quantity)+0 as pqty, count(cps.product_id) as services,
COUNT(CASE WHEN cps.status = 0 THEN cps.product_id END) as pending,
COUNT(CASE WHEN cps.status = 1 THEN cps.product_id END) as redeemed,
`t`.`created_at` as `date`, `c`.`name` as `pc`,
`sc`.`name` as `psc`, `p`.`expire_days` as `ped`,
`cps`.`customer_package_id` as `cpid` from `contacts`
left join `transactions` as `t` on `t`.`id` = `contacts`.`id`
left join `transaction_sell_lines` as `tsl` on `tsl`.`transaction_id` = `t`.`id`
inner join `customer_package` as `cp` on `contacts`.`id` = `cp`.`contact_id`
inner join `package` as `p` on `cp`.`package_id` = `p`.`id`
inner join `customer_package_service` as `cps` on `cps`.`customer_package_id` = `cp`.`id`
left join `categories` as `c` on `p`.`category_id` = `c`.`id`
left join `categories` as `sc` on `p`.`sub_category_id` = `sc`.`id`
where `contacts`.`id` != ?
and `contacts`.`deleted_at` is null
group by `cpid`
I just had to put the foreign name in first join I put the primary key which is wrong.
$contact_packages = Contact::where('contacts.id','!=',1)
->leftJoin('transactions as t','t.contact_id','=','contacts.id')
->leftJoin('transaction_sell_lines as tsl','tsl.transaction_id','=','t.id')
->join('customer_package as cp','contacts.id','=','cp.contact_id')
->join('package as p','cp.package_id','=','p.id')
->join('customer_package_service as cps','cps.customer_package_id','=','cp.id')
->leftJoin('categories as c','p.category_id','=','c.id')
->leftJoin('categories as sc','p.sub_category_id','=','sc.id')
// ->where('cps.customer_package_id','cp.id')
->select([
'contacts.id as cid',
'contacts.name as cname',
'p.id as pid',
'p.name as pname',
DB::raw('TRIM(tsl.quantity)+0 as pqty'),
// 'tsl.quantity as pqty',
DB::raw('count(cps.product_id) as services'),
DB::raw('COUNT(CASE WHEN cps.status = 0 THEN cps.product_id END) as pending'),
DB::raw('COUNT(CASE WHEN cps.status = 1 THEN cps.product_id END) as redeemed'),
't.created_at as date',
'c.name as pc',
'sc.name as psc',
'p.expire_days as ped',
'cps.customer_package_id as cpid'
])
->groupBy('cpid')
->get();
Related
I am currently working on a Lumen based application and I am stuck on an Eloquent/Laravel query. What I am currently working on is this:
$min = $filter['min_spending']*100;
$query = User::isCustomer()
->with("interests")
->leftJoin("points_history", "points_history.user_id", "=", "users.id")
->leftJoin("collections", "collections.user_id", "=", "users.id")
->select("users.*",
DB::raw("(SELECT SUM(amount) FROM points_history
WHERE points_history.user_id = users.id
AND points_history.confirmed = true ) as total_points"),
DB::raw("(SELECT SUM(price) FROM collections
WHERE paid_at IS NOT NULL
AND refunded_at IS NULL
AND collections.user_id = users.id) as total_purchase"),
DB::raw("(SELECT SUM(collections.price)) as current_purchase"))
->where("total_purchase", ">=", $min);
// other relevant code here
$query->groupBy('users.id')->orderBy('users.created_at', 'desc');
However, when I try to get the result, I get this error:
{"error":"SQLSTATE[42S22]: Column not found: 1054 Unknown column 'total_purchase >=' in 'where clause' (SQL: select count(*) as aggregate from `users` left join `points_history` on `points_history`.`user_id` = `users`.`id` left join `collections` on `collections`.`user_id` = `users`.`id` where `users`.`deleted_at` is null and `role` = 2 and `total_purchase >=` = 200000 group by `users`.`id`)"}
The subqueries did not seem to register which is causing the problem (?) My desired SQL Statement is this:
SELECT users . *,
(SELECT
SUM(amount)
FROM
points_history
WHERE
points_history.user_id = users.id
AND points_history.confirmed = true) AS total_points, (SELECT
SUM(price)
FROM
collections
WHERE
paid_at IS NOT NULL
AND refunded_at IS NULL
AND collections.user_id = users.id) AS total_purchase, SUM(collections.price) AS current_purchase
from
users
left join
points_history ON points_history.user_id = users.id
left join
collections ON collections.user_id = users.id
where
users.deleted_at is null AND (SELECT
SUM(price)
FROM
collections
WHERE
paid_at IS NOT NULL
AND refunded_at IS NULL
AND collections.user_id = users.id) >= 200000
GROUP BY users.id
where 200000 is $min. Could anyone help me pinpoint what the problem is in my query so I can figure out how to fix it?
You should try this:
$min = $filter['min_spending']*100;
$query = User::isCustomer()
->with("interests")
->leftJoin("points_history", "points_history.user_id", "=", "users.id")
->leftJoin("collections", "collections.user_id", "=", "users.id")
->select("users.*",
DB::raw("(SELECT SUM(amount) FROM points_history
WHERE points_history.user_id = users.id
AND points_history.confirmed = true ) as total_points"),
DB::raw("(SELECT SUM(price) FROM collections
WHERE paid_at IS NOT NULL
AND refunded_at IS NULL
AND collections.user_id = users.id) as total_purchase"),
DB::raw("(SELECT SUM(collections.price)) as current_purchase"))
->where("total_purchase", '>=', $min);
// other relevant code here
$query->groupBy('users.id')->orderBy('users.created_at', 'desc');
->where("total_purchase",">=", $min);
In the quick view, you did not put "," in the last line
FIXED:
Apparently, SELECT does not take multiple args but it accepts an array
->select(["users.*",
DB::raw("(SELECT SUM(amount) FROM points_history
WHERE points_history.user_id = users.id
AND points_history.confirmed = true ) as total_points"),
DB::raw("(SELECT SUM(price) FROM collections
WHERE paid_at IS NOT NULL
AND refunded_at IS NULL
AND collections.user_id = users.id) as total_purchase"),
DB::raw("(SELECT SUM(collections.price)) as current_purchase")]
Also ended up changing the WHERE clause to
$query->whereRaw(DB::raw("(SELECT SUM(amount) FROM points_history
WHERE points_history.user_id = users.id
AND points_history.confirmed = true ) <= " . $max));
with a dot instead of a comma to concatenate to the query
working in a section to get average rating for deals in same query and these are the details,
avg(rv.ratevalue) as avRatings
$this->db->join('product_rating rv','rv.productid = b.dealId','left');
$this->db->where('b.categoryId',$categoryId);
Which is returning 0 result which expected to be 4 . If i remove the category condition will return 4 insted of 0. Unable to detect the issue.
The full query is -
SELECT `b`.`deal_available_city`, `b`.`shippingType`, `b`.`priceType`, `b`.`dealId`, `b`.`dealUrl`, `b`.`dealTitle`, `b`.`slug`, `b`.`dealDetails`, `b`.`extraDetails`, `b`.`isHomeScreenBigDeal`, `b`.`deal_available_city`, `b`.`aditionalDetails`, `b`.`status`, `b`.`dateAdded`, `b`.`categoryId`, `b`.`siteId`, `b`.`isPinned`, `b`.`priceId`, `b`.`price`, `b`.`startDate`, `b`.`endDate`, `b`.`NumberOfClicked`, `b`.`discountPrice`, `b`.`discountPercentage`, `b`.`dealBrandId`, `b`.`endTime`, `b`.`startTime`, `b`.`howtousethisoffer`, `b`.`deal_location`, `b`.`cancellationpolicy`, `b`.`dealType`, `b`.`totalavailabledeals`, `b`.`numberofdealused`, `b`.`addedTime`, `i`.`thumbImage`, `i`.`imageUrl`, `i`.`normalimageurl`, `s`.`SiteUrl`, `s`.`SiteName`, `s`.`Site_alias`, `s`.`SiteLogo`, `c`.`cat_name`, `c`.`cat_color`, `c`.`cat_alias`, `p`.`price_name`, `p`.`price_symbol`, `p`.`price_shortcode`, `st`.`shId`, `st`.`shipping_text`, `l`.`user_id` as `isMarkedFavourite`, `dt`.`user_id` as `islikedorDisliked`, avg(rv.userid) as avRatings FROM `cob_dealdetails` as `b` LEFT JOIN `cob_dealImages` `i` ON `i`.`dealId` = `b`.`dealId` LEFT JOIN `cob_brand` `s` ON `s`.`SiteId` = `b`.`siteId` LEFT JOIN `cob_shipping_details` `st` ON `st`.`shId` = `b`.`shippingType` LEFT JOIN `cob_price_type` `p` ON `p`.`id` = `b`.`priceId` LEFT JOIN `cob_coupon_category` `c` ON `c`.`catId` = `b`.`categoryId` LEFT JOIN `cob_dealfavorite` `l` ON `l`.`deal_id` = `b`.`dealId` AND `l`.`user_id` = 3259 LEFT JOIN `cob_deallike` `dt` ON `dt`.`deal_id` = `b`.`dealId` AND `dt`.`user_id` = 3259 LEFT JOIN `cob_product_rating` `rv` ON `rv`.`productid` = `b`.`dealId` WHERE `b`.`showinhomescreen` = '1' AND `i`.`imgisdefault` = '1' AND `i`.`status` = '1' AND `i`.`imageOrder` = '1' AND FIND_IN_SET(1,b.deal_available_city) !=0 AND `b`.`startTime` <= '2017-07-22 19:00:09' AND `b`.`endTime` >= '2017-07-22 19:00:09' AND `b`.`categoryId` = '2' GROUP BY `b`.`dealId` ORDER BY `b`.`dealId` DESC LIMIT 10
I want to join two tables with two columns,
It's working in phpmyadmin. But it's not working with laravel.
So how to convert it in laravel structure.
SELECT
`j`.*,
`ts`.*,
`ps`.*,
`pn`.*,
`c`.*,
`planner`.*,
`ps`.`name` AS `section_name`,
`ps`.`id` AS `section_id`,
`planner`.`date` AS `planner_date`,
`pn`.`id` AS `planner_note_id`
FROM
`planner`
INNER JOIN
`timeslots` AS `ts` ON `ts`.`id` = `planner`.`timeslot_id`
INNER JOIN
`planner_sections` AS `ps` ON `ps`.`id` = `planner`.`planner_section_id`
LEFT JOIN
`planner_notes` AS `pn` ON `pn`.`date` = `planner`.`date` and `pn`.`contract_id` = `planner`.`contract_id`
INNER JOIN
`contracts` AS `c` ON `c`.`id` = `planner`.`contract_id`
INNER JOIN
`jobs` AS `j` ON `j`.`contract_id` = `c`.`id`
WHERE
`c`.`id` = 57
AND MONTH(`planner`.`date`) = 6
AND `planner`.`date` >= '2017-06-13'
AND `planner`.`deleted_at` IS NULL
ORDER BY `planner`.`date` ASC
But when i put it in laravel query structure it's not working.
$planner_list = Planner::join("timeslots as ts","ts.id","planner.timeslot_id")
->join("planner_sections as ps","ps.id","planner.planner_section_id")
->leftJoin("planner_notes as pn","pn.date","planner.date")
->leftJoin("planner_notes as pn","pn.contract_id","planner.contract_id")
->join("contracts as c","c.id","planner.contract_id")
->join("jobs as j","j.contract_id","c.id")
->where('c.id','=',$contract_id)
->where('planner.date','>=',$current_date)
->whereMonth('planner.date',$current_month)
->select(['j.*','ts.*','ps.*','pn.*','c.*','planner.*','ps.name as section_name','ps.id as section_id','planner.date as planner_date','pn.id as planner_note_id'])
->orderBy('planner.date','ASC')
->orderBy('planner.timeslot_id','ASC')
->orderBy('section_id','ASC')
->get();
Above conversation isn't working for me.
It's also not working with ,
->leftJoin("planner_notes as pn","pn.date","planner.date","pn.contract_id","planner.contract_id")
Edit :- No I'm not getting any errors for it. it just considering last On condition.
ON `pn`.`contract_id` = `planner`.`contract_id`
I have one more confusion that if I write two leftjoin then On condition can overwrite or not ?
EDIT-2 :-
It only returns last on condition.
Query from query log is :-
SELECT
`j`.*,
`ts`.*,
`ps`.*,
`pn`.*,
`c`.*,
`planner`.*,
`ps`.`name` AS `section_name`,
`ps`.`id` AS `section_id`,
`planner`.`date` AS `planner_date`,
`pn`.`id` AS `planner_note_id`
FROM
`planner`
INNER JOIN
`timeslots` AS `ts` ON `ts`.`id` = `planner`.`timeslot_id`
INNER JOIN
`planner_sections` AS `ps` ON `ps`.`id` = `planner`.`planner_section_id`
LEFT JOIN
`planner_notes` AS `pn` ON `pn`.`contract_id` = `planner`.`contract_id`
INNER JOIN
`contracts` AS `c` ON `c`.`id` = `planner`.`contract_id`
INNER JOIN
`jobs` AS `j` ON `j`.`contract_id` = `c`.`id`
WHERE
`c`.`id` = 57
AND MONTH(`planner`.`date`) = 6
AND `planner`.`date` >= '2017-06-13'
AND `planner`.`deleted_at` IS NULL
ORDER BY `planner`.`date` ASC
You could do
->leftJoin('planner_notes as pn', function($join){
$join->on('pn.date', '=', 'planner.date');
$join->on('pn.contract_id','=','planner.contract_id');
})
or
change alias of table as
->leftJoin("planner_notes as pn","pn.date",'=',"planner.date")
->leftJoin("planner_notes as pnotes","pnotes.contract_id",'=',"planner.contract_id")
Laravel join with multiple condition
LEFT JOIN
`planner_notes` AS `pn` ON `pn`.`date` = `planner`.`date` and `pn`.`contract_id` = `planner`.`contract_id`
it's equivalent to:
->leftJoin('planner_notes as pn', function($join){
$join->on('pn.date', '=', 'planner.date');
$join->on('pn.contract_id','=','planner.contract_id');
})
laravel.com Ref: method_on
Add an "on" clause to the join.
On clauses can be chained, e.g.
$join->on('contacts.userid', '=', 'users.id') ->on('contacts.infoid', '=', 'info.id')
will produce the following SQL:
on contacts.user_id = users.id and contacts.info_id = info.id
I am using following query to retrieve the user feeds but ordering latest update is not working when we applying order created_at time by desc
Here i have given SQL query. Kindly suggest me solution to solve my problem
select `users`.`id` as `uid`, `updates`.`post_id`, `updates`.`id` as `upid`, `friends`.`id` as `fid`, `updates`.`user_id`, `updates`.`privacy`, `updates`.`updated_at`, `updates`.`created_at`, `friends`.`first_user_id`, `friends`.`second_user_id`, `friends`.`friend_status`, `updates`.`update_type` from `updates`
inner join `users` on `updates`.`user_id` = `users`.`id`
inner join `friends` on
CASE
WHEN friends.first_user_id = 1
THEN friends.second_user_id = updates.user_id
WHEN friends.second_user_id= 1
THEN friends.first_user_id = updates.user_id
END
where `friends`.`friend_status` > 0
and `updates`.`privacy` in (1,2)
and `updates`.`user_id` != 1 and
`updates`.`deleted_at` is null
group by `updates`.`post_id`
order by `updates`.`created_at` desc
Laravel Code
Update::select(
'users.id as uid', 'posts.id as pid', 'updates.post_id', 'updates.id as upid',
'friends.id as fid', 'updates.user_id', 'updates.privacy', 'updates.updated_at', 'updates.created_at', 'posts.deleted_at', 'friends.first_user_id',
'friends.second_user_id', 'friends.friend_status', 'updates.update_type', 'posts.wall_user_id'
)->join('users', 'updates.user_id', '=', 'users.id')
->join('posts', 'posts.id', '=', 'updates.post_id')
->join('friends', function($join) use ($userId){
$join->on(DB::raw('CASE
WHEN friends.first_user_id = '.$userId.'
THEN friends.second_user_id = updates.user_id
WHEN friends.second_user_id= '.$userId.'
THEN friends.first_user_id = updates.user_id
END'
), DB::raw(''), DB::raw(''));
})->where('friends.friend_status', '>', 0)
->whereIn('updates.privacy', [1,2])
->where('updates.user_id', '!=', Auth::user()->id)
->groupBy('updates.post_id')
->orderBy('updates.created_at', 'DESC')
->get();
select * from(select `users`.`id` as `uid`, `updates`.`post_id`, `updates`.`id` as `upid`, `friends`.`id` as `fid`, `updates`.`user_id`, `updates`.`privacy`, `updates`.`updated_at`, `updates`.`created_at`, `friends`.`first_user_id`, `friends`.`second_user_id`, `friends`.`friend_status`, `updates`.`update_type` from `updates`
inner join `users` on `updates`.`user_id` = `users`.`id`
inner join `friends` on
CASE
WHEN friends.first_user_id = 1
THEN friends.second_user_id = updates.user_id
WHEN friends.second_user_id= 1
THEN friends.first_user_id = updates.user_id
END
where `friends`.`friend_status` > 0
and `updates`.`privacy` in (1,2)
and `updates`.`user_id` != 1 and
`updates`.`deleted_at` is null order by `updates`.`created_at` desc) as tmp_table
group by `updates`.`post_id`
I have a WordPress installation and I'm making a custom plugin. My plugin stores a good bit of usermeta. I'm using an inner join to combine data from the "users" and "usermeta" table at which point I spit the result back to my PHP script. Here's what my query looks like:
select
# Users table stuff
users.ID,
users.user_email,
users.display_name,
# Meta stuff
first_name.meta_value as first_name,
last_name.meta_value as last_name,
phone_number.meta_value as phone_number,
country.meta_value as country,
years_of_experience.meta_value as years_of_experience,
highest_degree_obtained.meta_value as highest_degree_obtained,
availability_for_work.meta_value as availability_for_work,
english_proficiency.meta_value as english_proficiency,
disciplines.meta_value as disciplines,
profile_picture.meta_value as profile_picture,
resume.meta_value as resume,
description.meta_value as description,
hourly_rate.meta_value as hourly_rate,
satisfaction_rating.meta_value as satisfaction_rating,
invited_projects.meta_value as invited_projects,
completed_project_count.meta_value as completed_project_count
# The table we're selecting from
from tsd_retro_users as users
# Join in our usermeta table for each individual meta value
inner join tsd_retro_usermeta first_name on users.ID = first_name.user_id
inner join tsd_retro_usermeta last_name on users.ID = last_name.user_id
inner join tsd_retro_usermeta phone_number on users.ID = phone_number.user_id
inner join tsd_retro_usermeta country on users.ID = country.user_id
inner join tsd_retro_usermeta years_of_experience on users.ID = years_of_experience.user_id
inner join tsd_retro_usermeta highest_degree_obtained on users.ID = highest_degree_obtained.user_id
inner join tsd_retro_usermeta availability_for_work on users.ID = availability_for_work.user_id
inner join tsd_retro_usermeta english_proficiency on users.ID = english_proficiency.user_id
inner join tsd_retro_usermeta disciplines on users.ID = disciplines.user_id
inner join tsd_retro_usermeta profile_picture on users.ID = profile_picture.user_id
inner join tsd_retro_usermeta resume on users.ID = resume.user_id
inner join tsd_retro_usermeta description on users.ID = description.user_id
inner join tsd_retro_usermeta hourly_rate on users.ID = hourly_rate.user_id
inner join tsd_retro_usermeta satisfaction_rating on users.ID = satisfaction_rating.user_id
inner join tsd_retro_usermeta invited_projects on users.ID = invited_projects.user_id
inner join tsd_retro_usermeta completed_project_count on users.ID = completed_project_count.user_id
# Define our select stipulations
where
(users.ID = 20)
and
(first_name.meta_key = 'first_name')
and
(last_name.meta_key = 'last_name')
and
(phone_number.meta_key = 'phone_number')
and
(country.meta_key = 'country')
and
(years_of_experience.meta_key = 'years_of_experience')
and
(highest_degree_obtained.meta_key = 'highest_degree_obtained')
and
(availability_for_work.meta_key = 'availability_for_work')
and
(english_proficiency.meta_key = 'english_proficiency')
and
(disciplines.meta_key = 'disciplines')
and
(profile_picture.meta_key = 'profile_picture')
and
(resume.meta_key = 'resume')
and
(description.meta_key = 'description')
and
(hourly_rate.meta_key = 'hourly_rate')
and
(satisfaction_rating.meta_key = 'satisfaction_rating')
and
(invited_projects.meta_key = 'invited_projects')
and
(completed_project_count.meta_key = 'completed_project_count')
As you can see, I inner join the usermeta table for each value that I'm trying to obtain from the database. It all seems to work fine, but after a certain number of inner joins, the query seems to slow to a crawl. Right now, the above query is taking about a second on average, and I only have about twenty users in my user table.
My question is: what are the performance ramifications of inner joins? Is there a better way to run the above query and achieve the same result?
Try this way:
select
# Users table stuff
users.ID,
users.user_email,
users.display_name,
# Meta stuff
MAX(CASE WHEN meta_table.meta_key='first_name' THEN meta_table.first_name ELSE NULL END) as first_name,
MAX(CASE WHEN meta_table.meta_key='last_name' THEN meta_table.last_name ELSE NULL END) as last_name,
MAX(CASE WHEN meta_table.meta_key='phone_number' THEN meta_table.phone_number ELSE NULL END) as phone_number,
MAX(CASE WHEN meta_table.meta_key='country' THEN meta_table.country ELSE NULL END) as country,
MAX(CASE WHEN meta_table.meta_key='years_of_experience' THEN meta_table.years_of_experience ELSE NULL END) as years_of_experience,
MAX(CASE WHEN meta_table.meta_key='highest_degree_obtained' THEN meta_table.highest_degree_obtained ELSE NULL END) as highest_degree_obtained,
MAX(CASE WHEN meta_table.meta_key='availability_for_work' THEN meta_table.availability_for_work ELSE NULL END) as availability_for_work,
MAX(CASE WHEN meta_table.meta_key='english_proficiency' THEN meta_table.english_proficiency ELSE NULL END) as english_proficiency,
MAX(CASE WHEN meta_table.meta_key='disciplines' THEN meta_table.disciplines ELSE NULL END) as disciplines,
MAX(CASE WHEN meta_table.meta_key='profile_picture' THEN meta_table.profile_picture ELSE NULL END) as profile_picture,
MAX(CASE WHEN meta_table.meta_key='resume' THEN meta_table.resume ELSE NULL END) as resume,
MAX(CASE WHEN meta_table.meta_key='description' THEN meta_table.description ELSE NULL END) as description,
MAX(CASE WHEN meta_table.meta_key='hourly_rate' THEN meta_table.hourly_rate ELSE NULL END) as hourly_rate,
MAX(CASE WHEN meta_table.meta_key='satisfaction_rating' THEN meta_table.satisfaction_rating ELSE NULL END) as satisfaction_rating,
MAX(CASE WHEN meta_table.meta_key='invited_projects' THEN meta_table.invited_projects ELSE NULL END) as invited_projects,
MAX(CASE WHEN meta_table.meta_key='completed_project_count' THEN meta_table.completed_project_count ELSE NULL END) as completed_project_count
# The table we're selecting from
from tsd_retro_users as users
# Join in our usermeta table for each individual meta value
inner join tsd_retro_usermeta as meta_table
ON users.ID = meta_table.user_id
# Define our select stipulations
where
(users.ID = 20)
GROUP BY users.ID
And as soon as we use php you can do this way:
$requiredMetaFields = array(
'first_name',
'last_name',
'phone_number',
'country',
'years_of_experience',
'highest_degree_obtained',
'availability_for_work',
'english_proficiency',
'disciplines',
'profile_picture',
'resume',
'description',
'hourly_rate',
'satisfaction_rating',
'invited_projects',
'completed_project_count'
);
$query = "select
users.ID,
users.user_email,
users.display_name,";
foreach($requiredMetaFields as $metafield) {
$query .= "MAX(CASE WHEN meta_table.meta_key='$metafield' THEN meta_table.$metafield ELSE NULL END) as $metafield, ";
}
$query =substr($query,0,-1);
$query .= "from tsd_retro_users as users
inner join tsd_retro_usermeta as meta_table
ON users.ID = meta_table.user_id
where
(users.ID = 20)
GROUP BY users.ID";
Edited syntax errors