Got this QueryBuilder in one of my repositories.
$query = $em->createQueryBuilder('d')
->select('d, i, u, SUM(CASE WHEN t.user = :userId THEN 1 ELSE 0 END) as myTickets')
->leftJoin('d.item','i')
->leftJoin('d.users','u')
->leftJoin('d.tickets','t')
->where('d.active = 1')
->andWhere('d.state = 1')
->setParameter('userId',$user->getId())
->orderBy('d.dateFinish', 'ASC');
When i execute the code, MySQL throws me this error.
Key "premium" for array with keys "0, myTickets" does not exist
"premium" is a field of "d".
How can i recive the fields with the custom SUM?
Since you're using aggregate function in your query, you get the so called mixed result. Mixed result normally return your object fetched with your FROM clause as zero index [0]. The rest of your result is populated based on the aliases you set for your custom fields.
$result[0] will return the object you want to access.
$result['myTickets'] will return the result of your aggregate function. In this case, it's a SUM.
A quote from documentation:
SELECT u, UPPER(u.name) nameUpper FROM MyProject\Model\User u
This query makes use of the UPPER DQL function that returns a scalar value and because there is now a scalar value in the SELECT clause, we get a mixed result.
Conventions for mixed results are as follows:
The object fetched in the FROM clause is always positioned with the key ‘0’.
Every scalar without a name is numbered in the order given in the query, starting with 1.
Every aliased scalar is given with its alias-name as the key. The case of the name is kept.
If several objects are fetched from the FROM clause they alternate every row.
You can read more about this topic here.
Related
Need some help with the MySQL query.
I have a table named custom_fields with attributes id, user_id, name, value etc.
name and values are of type string and it can store sometimes JSON also in the form of a string.
Requirement:
I need to list out all the unique user_id which satisfies below conditions
1) name must be starting with street_address_
2) value is a hash but stored as a string. if the country code is in ('us', 'in')
Here is the sample record.
id: 90489,
user_id: 30207,
name: "street_address_billing",
value:"{\"street_address1\":\"401 Lenora Street\",\"street_address2\":\"\",\"city\":\"Belltown\",\"locality\":\"Seattlel\",\"province\":\"WA\",\"postal_code\":\"111\",\"country_code\":\"us\"}",
deleted_at: nil,
active: true
Here is the query I'm trying. But it is not working. I have no error but it does not give any results either. instead of in if i use = and single value sometimes it gives the value.
SELECT id,user_id, #addr:= replace(replace(replace(replace(value, ':“', ':"'), '”,', '",'), '”}', '"}'), '{“' , '{"'), JSON_EXTRACT(#addr, '$.country_code') as billing_country
FROM `custom_fields` WHERE `custom_fields`.`active` = TRUE AND (name REGEXP '^street_address_')
AND JSON_EXTRACT(#addr, '$.country_code') in ('us', 'in');s
Despite the fact that SELECT syntax puts the select-list above the WHERE clause, WHERE conditions are evaluated first, to restrict the rows returned by the query. Then for those rows only, expressions in the select-list are evaluated. So your variables defined in the select-list cannot be used in the WHERE clause.
So you need to reference the column itself in your WHERE conditions:
SELECT id,user_id, JSON_UNQUOTE(JSON_EXTRACT(value, '$.country_code')) AS billing_country
FROM `custom_fields` WHERE `custom_fields`.`active` = TRUE AND (name REGEXP '^street_address_')
AND JSON_UNQUOTE(JSON_EXTRACT(value, '$.country_code')) IN ('us', 'in');
Also you need to use JSON_UNQUOTE() because the return value of JSON_EXTRACT() is not a plain string — it's a JSON document that happens to be a scalar. So it will return "us".
I've removed all the replace() stuff because you shouldn't need it. If you use JSON data, you should store it in a JSON column, and that will reject invalid JSON that contains smart-quote characters.
I want to obtain unread messages count from MySQL database using SELECT SUM operator.
So, my SQL is:
SELECT sum(status_field = 'new') unreadMessagesCount
FROM messages
WHERE 'author_uid' = 'authorUID'
And it returns NULL. Why?
I have items in database and I can select it by (SELECT * FROM messages)
It returns NULL because you are comparing strings, not columns with:
WHERE 'author_uid' = 'authorUID'
And these two strings are not equal. So, all rows are filtered out. The NULL value is because you have an aggregation query. SUM() returns NULL when there are no rows in such a query.
I'm not sure what you intend. Perhaps:
WHERE author_uid = 'authorUID'
However, 'authorUID' seems like a strange value for a uid. You need to put an appropriate value there. If it is a string, enclose it in single quotes. If it is a number, do not use single quotes.
I'm reading MySQL's documentation on the assignment operators, and in the section for the := operator, it says
The value on the right hand side may be a literal value, another variable storing a value, or any legal expression that yields a scalar value, including the result of a query (provided that this value is a scalar value).
If I understand correctly, a scalar value is a value that represents a fixed value instead of a range or collection of values or an object.
Being very new to SQL in general, I don't quite understand the parenthetical statement at the end of the quote. When would the result of a query be a non-scalar value? Is it when a query simply returns multiple columns from a row in its result? If so, how can those results be used meaningfully in a MySQL script if they can't be stored in a variable?
Such a query is a scalar subquery. Such a subquery has two important properties:
The subquery returns exactly one column.
The subquery returns at most one row.
If the subquery returns no rows, then the assigned value is NULL.
That is a subquery. You can assign multiple values using SELECT and :=:
select #var1 := col1, #val2 := col2
from . . .;
A scalar value has one column and one row. You can't assign such multi-valued results to a MySQL session variable.
But you can assign multiple columns to multiple variables.
SELECT a, b, c FROM mytable INTO #varA, #varB, #varC;
See http://dev.mysql.com/doc/refman/5.7/en/select-into.html for more details.
I'm working with iReport Designer and JasperServer 5.6 on a MySQL database and I'm trying to make my report return all results when the parameter is null.
I've been looking at the documentation here: http://jasperreports.sourceforge.net/sample.reference/query/, which has been quite helpful except it doesn't have what I want. The closest I've gotten is here in the documentation:
The $X{EQUAL, column_name, parameter_name} clause function
The function expects three mandatory clause tokens:
The first token represents the function ID and always takes the fixed value EQUAL.
The second token is the SQL column (or column combination) to be used in the clause.
The third token is the name of the report parameter that contains the value to compare to.
If the parameter's value is not null, the function constructs a
= ? clause. If the parameter's value is null, the
function generates a IS NULL clause.
All the parameters I'm inputting are the id's of the records I'd like to see, so when I use this I get no results because an id or the Primary Key cannot be null.
Ex.
SELECT *
FROM User
WHERE $X{EQUAL, user.id, user_id}
Inputting 1 will return user id 1 and inputting nothing, or null, will return me nothing. What I want it to return instead is all users in the table.
Is there an easy fix to this problem, like having this function return IS NOT NULL when this happens? Is there something else in JasperServer or iReports that will help me or is there something I can do in SQL that will ignore a WHERE clause when I have this parameter set to null?
You can use the below logic in your query's WHERE clause to achieve what you are asking (this works in postgres, but it should work in MySQL as well):
where (($P{parameter1} is null) or (user.id = $P{parameter1}))
If the parameter is null the first part of the OR comparator will return true, and the query will ignore the rest of the expression, which should give you all users in the user table. If it is not null, it will skip over the first part and execute the query for the user.id passed to the parameter.
Hope this helps!
I would like to do something like this
User.select("users.id, count(whatever) as test")
But rails return only the User.id without the count.
I can't use something like
User.count(whatever)
Because I use this select in a very complex SQL query. Is it possible to get the count value with select helper ?
Are you sure the following query returns User.id? Doesn't it throw an error saying "column is invalid in the select list because it is not contained in either an aggregate function or the group by clause":
User.select("users.id, count(whatever) as test")
Because you are using count you should also use group method as following:
User.select("users.id, count(whatever) as test").group("users.id, whatever")
Then your resultant array will contain users.id and count(whatever).