Raw Sub Query inside selectRaw - mysql

BowlerMaster::selectRaw("
tour_id, bowler_id, bowler_name, ball_team,
SUM(balls) AS balls,
SUM(overs) AS overs,
DB::raw('SELECT runs, wicket FROM bowler_master WHERE tour_id = ".$request->tour_id." AND bowler_id = ".$request->player_id." ORDER BY wicket DESC, runs LIMIT 1 AS bbi')
")
->where($where_array)
->groupby(['tour_id','bowler_id'])
->get()->first();
In the above Eloquent Query I want to use raw query or any other wayout for getting the result of the raw query to get the value of bbi, but I am getting the following error :
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '::raw('SELECT match_id, runs, wicket FROM bowler_master WHERE tour_id = 1 AND bo' at line 25.
I am writing writing this query for generating following output,
{
"status": 200,
"message": "Success",
"bowler": {
"tour_id": 1,
"bowler_id": 21,
"bowler_name": "Kaushal Chauhan",
"ball_team": null,
"balls": "29",
"overs": 4.5,
"bbi": 9/3,
}
}
Uptil overs calculation, everything is working fine. I am not getting how to get the "bbi" key:value
Note: The result of the query will be pushed in response array and will be converted into json to get the output shown above.
Please guide.

Try this
BowlerMaster::selectRaw("tour_id, bowler_id, bowler_name, ball_team, SUM(balls) AS balls,SUM(overs) AS overs")
->selectSub("
SELECT runs
FROM bowler_master
WHERE tour_id = ".$request->tour_id."
AND bowler_id = ".$request->player_id."
ORDER BY wicket DESC, runs LIMIT 1
","runs")
->selectSub("
SELECT wicket
FROM bowler_master
WHERE tour_id = ".$request->tour_id."
AND bowler_id = ".$request->player_id."
ORDER BY wicket DESC, runs LIMIT 1
","wicket")
->where($where_array)
->groupby(['tour_id','bowler_id'])
->get()->first();
The rules of writing select sub query in laravel is as follows:
DB::table('tablename')
->select('column name','..')
->selectSub("Your full query","alias name")
->get()

Related

Want to use this but giving error in syntax help me to fix permanent in Query Builder Codeigniter

SELECT installation
FROM `id`
WHERE `outlet_id` = '9'
AND `status` = '1'
GROUP BY `page_rank` `asc`
ORDER BY `page_rank=0`
LIMIT -1, 1
Page Rank=0 gives error
You have an error in your SQL syntax; check the manual that
corresponds to your MariaDB server version for the right syntax to use
near 'asc ORDER BY page_rank=0 LIMIT -1, 1' at line 5
Query using codeigniter query builder class -
$this->db->select('installation') // column name
$this->db->from('id'); // table name
$this->db->where('outlet_id', 9); // condition
$this->db->where('status', 1);
$this->db->group_by('page_rank');
$this->db->order_by('page_rank', 'ASC');
$this->db->limit(1, 0); // will show 1 result starting from 0 ie first result
$query = $this->db->get()->result();
return $query;
Produces
SELECT installation
FROM `id`
WHERE `outlet_id` = 9
AND `status` = 1
GROUP BY `page_rank`
ORDER BY `page_rank` ASC
LIMIT 0, 1
See if it solves your issue.

How to put SQL request in QueryBuilder and avoid ``?

I have this SQL request in MySQL
SELECT * FROM pt WHERE id=98 ORDER BY FIELD (position, 4, 3, 2, 1, 5)
and I need to make a query in Yii2. When I write
'query' => Pt::find()->where(['id' => $model->id])
->OrderBy('FIELD (`position`, 4, 3, 2, 1, 5)')
I receive
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'LIMIT 20' at line 1
The SQL being executed was: SELECT * FROM `pt` WHERE `id`=98 ORDER BY FIELD (`position`, `4`, `3`, `2`, `1`, `5)` LIMIT 20
How to avoid `` in request?
Use yii\db\Expression class as it'll help you to insert RAW code (without formatting it in generated queries), but be cautious! Do not insert user input as RAW in DB queries, being that it leads to severe vulnerabilities.
The working code looks as follow:
'query' => Pt::find()->where(['id' => $model->id])
->orderBy(new \yii\db\Expression('FIELD (`position`, 4, 3, 2, 1, 5)'))

Doctrine 1 select column with duplicate values

I have a query that will display columns with duplicate or with more than 1 values.I can display it using sql
select date_created,loan_id,count(1) as cnt
from collections
group by date_created,loan_id
having count(1)>1;
I want that to convert to Doctrine 1 query,I tried
public function getDuplicateDatePayment() {
$q = $this->createQuery('c')
->select('c.date_created,c.loan_id,c.count(1) as cnt')
->groupBy('c.date_created','c.loan_id')
->having('c.count(1) > 1');
return $q->execute();
}
But it only return errors.Any Idea on how to correctly convert the said working sql into a doctrine 1 query?
SQLSTATE[42000]: Syntax error or access violation: 1630 FUNCTION c.count does not exist. Check the 'Function Name Parsing and Resolution' section in the Reference Manual. Failing Query: "SELECT c.id AS c__id, c.date_created AS c__date_created, c.loan_id AS c__loan_id, c.count(1) AS c__0, c.count(1) AS c__0 FROM collections c GROUP BY c.date_created HAVING c.count(1) > 1"
I hope the problem may be with count. Try the following
public function getDuplicateDatePayment() {
$q = $this->createQuery('c')
->select('c.date_created,c.loan_id,count(c.1) as cnt')
->groupBy('c.date_created','c.loan_id')
->having('c.count(1) > 1');
return $q->execute();
}

#1327 - Undeclared variable: table_name

I was rolling some queries into a stored procedure and I hit the #1327 - Undeclared variable error ... the odd thing though is that the variable it claims is undeclared is actually a table name.
Working through the problem
So I extracted the bit of the procedure where it was falling over and tried to run it as a normal SQL query directly on the database through PHPMyAdmin... same thing. After much tinkering it seems to be where I'm joining another table.
If I run the query on a single table, it's fine, like this:
SET #i_channel_id = 3;
SET #i_product_id = 90;
SELECT
`product_status_to_channel`.`status_code` INTO #s_status_code
FROM `product_status_to_channel`
WHERE `product_status_to_channel`.`channel_id` = #i_channel_id
AND `product_status_to_channel`.`product_id` = #i_product_id
ORDER BY IF(`product_status_to_channel`.`date` IS NULL, 1, 0) ASC,
`product_status_to_channel`.`date` DESC
LIMIT 0, 1;
SELECT #s_status_code AS status_code;
Which outputs 'LIVE' as the status_code in PHPMyAdmin - which is fine.
However, when I try and JOIN to the message table to find the associated status message, I get the error: #1327 - Undeclared variable: product_status_to_channel_lang ... but product_status_to_channel_lang is a table?!
SET #i_channel_id = 3;
SET #i_language_id = 3;
SET #i_product_id = 90;
SELECT
`product_status_to_channel`.`status_code` INTO #s_status_code,
`product_status_to_channel_lang`.`string` INTO #s_status_message
FROM `product_status_to_channel`
LEFT JOIN `product_status_to_channel_lang`
ON `product_status_to_channel`.`product_status_to_channel_id` = `product_status_to_channel_lang`.`product_status_to_channel_id`
AND `product_status_to_channel_lang`.`language_id` = #i_language_id
WHERE `product_status_to_channel`.`channel_id` = #i_channel_id
AND `product_status_to_channel`.`product_id` = #i_product_id
ORDER BY IF(`product_status_to_channel`.`date` IS NULL, 1, 0) ASC, `product_status_to_channel`.`date` DESC
LIMIT 0, 1;
SELECT #s_status_code AS status_code, #s_status_message AS status_message;
Is it trying to evaluate product_status_to_channel_lang.product_status_to_channel_id as a variable on the JOIN?
LEFT JOIN `product_status_to_channel_lang`
ON `product_status_to_channel`.`product_status_to_channel_id` = `product_status_to_channel_lang`.`product_status_to_channel_id`
I assume I'm overlooking something obvious?
I've tried this on both:
a Win7 box running xampp with MySQL 5.5.27 - MySQL Community Server (GPL)
a Debian box running MySQL 5.1.73-1-log - (Debian)
Never mind - it was something obvious:
SELECT
`product_status_to_channel`.`status_code` INTO #s_status_code,
`product_status_to_channel_lang`.`string` INTO #s_status_message
Should be:
SELECT
`product_status_to_channel`.`status_code`,
`product_status_to_channel_lang`.`string`
INTO
#s_status_code,
#s_status_message
... it must be Friday, it took literally a couple of hours to see that.
... INTO #s_status_code,
`product_status_to_channel_lang`.`string` ...
^That's where it's trying to assign product_status_to_channel_lang to being a variable into which to put data.

How to group by SqlFunction with VarArgsSQLFunction in NHibernate

I'm trying to implement the following SQL query with QueryOver:
SELECT [Time]/1000
FROM TableName
GROUP BY [Time]/1000
Here's my current attempt:
var result = session
.QueryOver<TableName>
.Select(Projections.GroupProperty(
Projections.SqlFunction(
new VarArgsSQLFunction("(", "/", ")"),
NHibernateUtil.Int64,
Projections.Property("Time")
Projections.Constant(1000))
))
.List<object>();
Unfortunately I get the following exception (GenericADOException):
could execute query
[ SELECT (this_.Time/#p0) as y0_ FROM [TableName] this_ GROUP BY (this_.Time/?) ]
And the inner exception:
Incorrect syntax near ?.
I can replace the "GroupProperty" with a "Sum" and it works. Any idea what's missing?
Update:
Apparently it's a bug in NHibernate. See also this question.
Why don't you just use Projections.SqlGroupProjection:
var result = session
.QueryOver<TableName>
.Select(Projections.SqlGroupProjection(
Time/1000 AS TimeValue",
"Time/1000",
new[]{"TimeValue"},
new[]{NHibernateUtil.Int32}))
.List<object>();