How can I translate a SQL query like this to Eloquent or QueryBuilder :
SELECT * FROM studies
where studies.id in(SELECT study_id FROM (
SELECT max(studies.end_date), studies.id as study_id
from workers inner join resumes on workers.id=resumes.worker_id
inner join studies on resumes.id=studies.resume_id where
resumes.title="main" group by workers.id) as SQ2
Or globally
How can we make select from other select statement with eloquant for exemple:
SELECT a.id from (SELECT * FROM A INNER JOIN B ON a.id=b.id where a.id > 10) as SUBQ1
I think your current query doesn't get study_id with max end_date in all cases, you can try this one:
SELECT * FROM studies
where studies.end_date in (
SELECT max(studies.end_date)
from workers inner join resumes on workers.id=resumes.worker_id
inner join studies on resumes.id=studies.resume_id where
resumes.title="main" group by workers.id)
and if you want implement that with laravel Eloquant you can do it like this:
$result = DB::table('studies')
->select("*")
->whereIn('end_date', function($query){
$query->selectRaw("max(studies.end_date) as max_date")
->from('workers')
->join('resumes', 'workers.id', '=', 'resumes.worker_id')
->join('studies', 'resumes.id', '=', 'studies.resume_id')
->where('resumes.title', '=', 'main')
->groupBy('workers.id');
})
->get();
foreach($result as $row) {
print_r($row);
}
Related
I want to view bonus recapitulation from transaction and i try write code in phpmyadmin like
SELECT
tbl2.name, b.nama_bonus,
SUM(
CASE
WHEN b.nama_bonus REGEXP 'saldo' THEN tbl2.jumlah_transaksi * b.nominal_bonus
WHEN b.nama_bonus REGEXP 'bintang' AND tbl2.nama_kategori REGEXP 'transfer' THEN FLOOR(tbl2.total_nominal_transaksi / b.keterangan_bonus)
ELSE FLOOR(tbl2.total_nominal_transaksi / b.keterangan_bonus)
END
) AS bonus_member
FROM
(
SELECT tbl1.*, u.name, pc.nama_kategori, COUNT(tbl1.nominal_transaksi) AS jumlah_transaksi, SUM(tbl1.nominal_transaksi) AS total_nominal_transaksi FROM
(
SELECT no_invoice, product_category_id, nominal_transaksi, user_id, status_transaksi_id FROM transactions
WHERE status_transaksi_id = 1
) AS tbl1
JOIN users u ON u.id = tbl1.user_id
JOIN product_categories pc ON pc.id = tbl1.product_category_id
GROUP BY u.id, pc.id
) AS tbl2
JOIN bonus b ON b.product_category_id = tbl2.product_category_id
GROUP BY b.nama_bonus, tbl2.name
ORDER BY tbl2.name
And the result is result query image
how to implement mysql code with eloquent using yajra datatables and also filter the data?
How do this query in laravel query builder ?
select * from products p join
(
select product_id,sum(qty) total_sales
from orders where qty !=0 group by product_id
)
s on p.id = s.product_id
order by s.total_sales desc
There are different ways are there to do the same thing. But you can do with Raw Expressions is very similar to your above code.
if you want to use Eloquent, Do this provided the orders table has product_id that is a foreign key from products
DB::table('products')->join('orders','products.id','orders.product_id')->where('orders.qty','!=',0)->get()
The first part for sub-query for joined part. It is joined with toSql() method inside the raw statement.
$subQuery = DB::table('orders')
->where('qty', '!=', DB::raw(0))
->groupBy('product_id')
->select('product_id', DB::raw('sum(qty) as total_sales'));
return DB::table('products as p')
->join(DB::raw('(' . $subQuery->toSql() . ') s'), 'p.id', '=', 's.product_id')
->orderByDesc('s.total_sales')
->get();
It prints the following sql;
SELECT *
FROM `products` AS `p`
INNER JOIN (
SELECT `product_id`, SUM(qty) AS total_sales
FROM `orders`
WHERE `qty` != 0
GROUP BY `product_id`
) s ON `p`.`id` = `s`.`product_id`
ORDER BY `s`.`total_sales` DESC
How I can convert this MySQL query to a Laravel query?
select *
from marques
where id in (select marque_id from products
where category_id = 'valeur1' or category_id in (select id from categories
where parent_id = 'Valeur1'))
I think your current query is equivalent to the following:
SELECT *
FROM marques m
LEFT JOIN products p
ON m.id = p.marque_id
LEFT JOIN categories c
ON p.category_id = c.id AND c.parent_id = 'Valeur1'
WHERE
p.category_id = 'valeur1' OR
c.id IS NOT NULL
Here is a rough guess at what your Laravel code might look like:
$res = DB::table('marques')
->join('products', 'marques.id', '=', 'products.marque_id')
->join("categories", function($join) {
$join->on('products.category_id', '=', 'categories.id')
->on('categories.parent_id', '=', 'Valeur1')
})
->whereNotNull('categories.id')
->orWhere('products.category_id', '=', 'valeur1')
->select('*')
->get();
My date in table is TIMESTAMP something like this 2016-05-28 18:39:00
Now I am trying to select from table where date = 2016-05-28
here is my query
$getReport = $db->prepare('SELECT a.proId, a.userId, DATE(a.date), a.status, a.canceledBy, b.id, b.pName, b.pPrice FROM purchaseshistory AS a INNER JOIN products AS b ON(a.proId=b.id) WHERE a.date=?');
$getReport->bind_param('i', $dateOfBirth);
$getReport->execute();
$getReport->bind_result($proId, $userId, $date, $status, $canceledBy, $id, $pName, $pPrice);
$getReport->store_result();
while ($getReport->fetch()) {
Date is coming from here
$dateOfBirth = $_POST['dateOfBirth'];
results are empty
could be you need a correct date format
SELECT a.proId, a.userId,
DATE(a.date), a.status, a.canceledBy, b.id, b.pName, b.pPrice
FROM purchaseshistory AS a
INNER JOIN products AS b ON(a.proId=b.id)
WHERE date_format(a.date,'%Y-%m-%d') = ?
You've converted a.date to a DATE in the SELECT, but not in the WHERE clause, I would recommend modifying your query as below:
SELECT
ph.proId, ph.userId, DATE(ph.date), ph.status, ph.canceledBy,
p.id, p.pName, p.pPrice
FROM purchaseshistory AS ph
INNER JOIN products AS p ON ph.proId = p.id
WHERE DATE(ph.date) = ?
I am trying to convert my mysql statement into laravel query builder. In the following query I am trying to do GROUP BY and ORDER BY on the columns which are fetched from the result of UNION-ing three tables
staff_task_history_calibrate
staff_task_history_samples
staff_task_history_measures
Have you guys come across anything similar to it? If yes, could you please shed some light on my issue?
SELECT staff_name, task_id, task_type, task_desc, SUM(task_multiplier)
FROM
(
(
select CONCAT(S.first_name," ",S.last_name) as staff_name,
`STHC`.`task_id`, IFNULL(T.type, "-") as task_type,
`T`.`description` as `task_desc`,
STHC.task_multiplier
from `staff_task_history_calibrate` as `STHC`
inner join `staffs` as `S` on `STHC`.`staff_id` = `S`.`staff_id` inner join `tasks` as `T` on `STHC`.`task_id` = `T`.`id`
)
union
(
select CONCAT(S.first_name," ",S.last_name) as staff_name,
`STHS`.`task_id`, IFNULL(T.type, "-") as task_type,
`T`.`description` as `task_desc`,
STHS.task_multiplier
from `staff_task_history_samples` as `STHS`
inner join `staffs` as `S` on `STHS`.`staff_id` = `S`.`staff_id` inner join `tasks` as `T` on `STHS`.`task_id` = `T`.`id`
)
union
(
select CONCAT(S.first_name," ",S.last_name) as staff_name,
`STHM`.`task_id`, IFNULL(T.type, "-") as task_type,
`T`.`description` as `task_desc`,
STHM.task_multiplier
from `staff_task_history_measures` as `STHM`
inner join `staffs` as `S` on `STHM`.`staff_id` = `S`.`staff_id` inner join `tasks` as `T` on `STHM`.`task_id` = `T`.`id`
)
) combined_tables
GROUP BY staff_name, task_type, task_desc
ORDER BY staff_name, task_type, task_desc;
Difficult for me to test, but try:
// Build up the sub-queries
$sub1 = DB::table('staff_task_history_calibrate AS STHC')
->select(DB::raw(
'CONCAT(S.first_name," ",S.last_name) as staff_name',
'STHC'.'task_id', 'IFNULL(T.type, "-") as task_type',
'T'.'description' as 'task_desc', 'STHC.task_multiplier')
)->join('staffs AS S', 'STHC.staff_id', '=', 'S.staff_id')
->join('tasks AS T', 'STHC.task_id', '=', 'T.id');
$sub2 = DB::table('staff_task_history_samples AS STHS')
->select(DB::raw(
'CONCAT(S.first_name," ",S.last_name) as staff_name',
'STHS'.'task_id', 'IFNULL(T.type, "-") as task_type',
'T'.'description' as 'task_desc', 'STHS.task_multiplier')
)->join('staffs AS S', 'STHS.staff_id', '=', 'S.staff_id')
->join('tasks AS T', 'STHS.task_id', '=', 'T.id');
$sub3 = DB::table('staff_task_history_measures AS STHM')
->select(DB::raw(
'CONCAT(S.first_name," ",S.last_name) as staff_name',
'STHM'.'task_id', 'IFNULL(T.type, "-") as task_type',
'T'.'description' as 'task_desc', 'STHM.task_multiplier')
)->join('staffs AS S', 'STHM.staff_id', '=', 'S.staff_id')
->join('tasks AS T', 'STHM.task_id', '=', 'T.id');
// Add the unions
$allUnions = $sub1->union($sub2)->union($sub3); // (Check the documentation for Unions in Query Builder)
// Get the results
$results = DB::table(DB::raw("({$allUnions->toSql()}) as combined_tables"))
->select('staff_name, task_id, task_type, task_desc')
->sum('task_multiplier')
->mergeBindings($allUnions) // We need to retrieve the underlying SQL
->groupBy('staff_name')
->groupBy('task_type')
->groupBy('task_desc')
->orderBy('staff_name')
->orderBy('task_type')
->orderBy('task_desc')
->get();
(If what you have works, I'd keep it.)