i try to join multiple Tables in one Query.
My Entitie Relations:
Person
Entities\Person:
type: entity
table: person
manyToOne:
address:
targetEntity: Address
joinColumn:
name: idaddress
referencedColumnName: idaddress
manyToMany:
tags:
targetEntity: Tag
joinTable:
name: persons_tags
joinColumns:
person_idperson:
referencedColumnName: idperson
inverseJoinColumns:
tag_idtag:
referencedColumnName: idtag
Tag
Entities\Tag:
type: entity
table: tag
manyToMany:
sms:
targetEntity: Sms
mappedBy: tag
sms
manyToMany:
tag:
targetEntity: Tag
joinTable:
name: sms_tags
joinColumns:
sms_idsms:
referencedColumnName: idsms
inverseJoinColumns:
tag_idtag:
referencedColumnName: idtag
This is a valid working SQL Statement:
SELECT DISTINCT person.lastname, person.firstname, address.mobileprivate, address.mobilebusiness FROM
`address`,
`person`,
`persons_tags`,
`sms_tags`
WHERE
person.idaddress = address.idaddress
AND person.idperson = persons_tags.person_idperson
AND persons_tags.tag_idtag = sms_tags.tag_idtag
AND sms_tags.sms_idsms = (myINPUT)
Now i try to join the needed Entities in DQL to get the same result:
SELECT DISTINCT s, t, p, a
FROM Entities\Sms s
JOIN s.sms_idsms t
JOIN t.person_idperson p
JOIN p.idaddress a
WHERE s.idsms = (myINPUT)
But i only get an error:
PHP Fatal error: Uncaught exception 'Doctrine\\ORM\\Query\\QueryException' with message '
SELECT DISTINCT s, t, p, a
FROM Entities\\Sms s
JOIN s.sms_idsms t
JOIN t.person_idperson p
JOIN p.idaddress a
WHERE s.idsms = 2' in
/var/www/ci_doc_rem/Codeigniter_Doctrine/source/application/libraries/Doctrine/ORM/Query/QueryException.php:39
Stack trace:
#0 /var/www/ci_doc_rem/Codeigniter_Doctrine/source/application/libraries/Doctrine/ORM/Query/Parser.php(429): Doctrine\\ORM\\Query\\QueryException::dqlError('SELECT DISTINCT...')
#1 /var/www/ci_doc_rem/Codeigniter_Doctrine/source/application/libraries/Doctrine/ORM/Query/Parser.php(925): Doctrine\\ORM\\Query\\Parser->semanticalError('Class Entities\\...')
#2 /var/www/ci_doc_rem/Codeigniter_Doctrine/source/application/libraries/Doctrine/ORM/Query/Parser.php(1561): Doctrine\\ORM\\Query\\Parser->JoinAssociationPathExpression()
#3 /var/www/ci_doc_rem/Codeigniter_Doctrine/source/application/libraries/Doctrine/ORM/Query/Parser.php(1506): Doctrine\\ORM\\Query\\Parser->JoinAssociationDeclaration()
#4 /var/www/ci_ in /var/www/ci_doc_rem/Codeigniter_Doctrine/source/application/libraries/Doctrine/ORM/Query/QueryException.php on line 49
How to write a DQL Query like the working SQL Query?
I try to avoid a native SQL Query
Here is a try with the Query Builder:
$qb->select(array('s', 't', 'p', 'a'))
->from('Entities\Sms', 's')
->leftJoin('s.tag', 't')
->leftJoin('t.person', 'p')
->leftJoin('p.address', 'a')
->where('s.idsms = 1');
And the Error Message
PHP Fatal error: Uncaught exception 'Doctrine\\ORM\\Query\\QueryException' with message 'SELECT s, t, p, a FROM Entities\\Sms s LEFT JOIN s.tag t LEFT JOIN t.person p LEFT JOIN p.address a WHERE s.idsms = 1' in /var/www/ci_doc_rem/Codeigniter_Doctrine/source/application/libraries/Doctrine/ORM/Query/QueryException.php:39\nStack trace:\n#0 /var/www/ci_doc_rem/Codeigniter_Doctrine/source/application/libraries/Doctrine/ORM/Query/Parser.php(429): Doctrine\\ORM\\Query\\QueryException::dqlError('SELECT s, t, p,...')\n#1 /var/www/ci_doc_rem/Codeigniter_Doctrine/source/application/libraries/Doctrine/ORM/Query/Parser.php(925): Doctrine\\ORM\\Query\\Parser->semanticalError('Class Entities\\...')\n#2 /var/www/ci_doc_rem/Codeigniter_Doctrine/source/application/libraries/Doctrine/ORM/Query/Parser.php(1561): Doctrine\\ORM\\Query\\Parser->JoinAssociationPathExpression()\n#3 /var/www/ci_doc_rem/Codeigniter_Doctrine/source/application/libraries/Doctrine/ORM/Query/Parser.php(1506): Doctrine\\ORM\\Query\\Parser->JoinAssociationDeclaration()\n#4 /var/www/ci_doc_rem/Cod in /var/www/ci_doc_rem/Codeigniter_Doctrine/source/application/libraries/Doctrine/ORM/Query/QueryException.php on line 49
The Solution was to easy to find.
I've replaced the idname namingconvention just by 'id' for every table / entitie and had a closer look to Picking Owning and Inverse Side.
http://docs.doctrine-project.org/en/latest/reference/association-mapping.html#picking-owning-and-inverse-side
This enabled me to write correct Relations.
A big Problem for me, was to decode the Debug Stack Trace to find my error.
Thanks to anyone who spend time to solve my Problem!
Related
SELECT
ps.hotel_id,
ps.name,
ps.country,
ps.city,
ps.chain_name,
ps.account_manager,
ps.adf_2_0,
t.booker_cc1,
sum(kpi.as_booked_roomnights) as ABRN,
sum(kpi.booked_roomnights) as BRN,
sum(kpi.cancelled_roomnights) as CRN,
sum(kpi.booked_price_euro) as booked_rev,
sum(kpi.stayed_roomnights) as SRN,
sum(kpi.stayed_price_euro) as stayed_rev,
sum(kpi.as_booked_commission_euro) as abc,
FROM reporting.kpi_booked_cancelled_stayed kpi
JOIN reporting.property_splits ps ON kpi.hotel_id=ps.hotel_id
JOIN fpa.transactions_detail t ON ps.hotel_id = t.hotel_id
where
to_date(kpi.yyyy_mm_dd) BETWEEN '2020-01-01' AND '2020-01-05'
AND ps.region ='APAC'
AND ps.is_global_chain ='1'
AND ps.is_open_bookable ='1'
GROUP BY 1,2,3,4,5,6,7
Hi, I wanted to extract some tables from hive and combine them together. However I got some error. Here is what I got:
***error while compiling statement: FAILED: ParseException line 17:0 cannot recognize input near 'FROM' 'reporting' '.' in selection target
Extra comma here:
sum(kpi.as_booked_commission_euro) as abc, --remove comma
I have a question about query builder.
I wanna made a query that will have conection with two databases
I will show you the SQL query :
SELECT
naviones_db16.ps_orders.payment,
naviones_db16.ps_orders.total_paid AS total,
naviones_db16.ps_orders.current_state AS current_state,
naviones_db16.ps_orders.id_order AS id_order,
naviones_db16.ps_shop.NAME AS name_shop,
naviones_db16.ps_customer.firstname AS customer_firstname,
naviones_db16.ps_customer.lastname AS customer_lastname,
naviones_db16.ps_orders.reference,
naviones_db16.ps_orders.date_add AS fecha
FROM
ps_orders
INNER JOIN naviones_db16.ps_customer ON
naviones_db16.ps_customer.id_customer=
naviones_db16.ps_orders.id_customer
INNER JOIN naviones_db16.ps_shop ON naviones_db16.ps_shop.id_shop =
naviones_db16.ps_orders.id_shop
WHERE
naviones_db16.ps_orders.current_state = 16
AND
naviones_db16.ps_orders.id_order NOT IN (
SELECT
multimarket.productos.id_order
FROM
multimarket.productos
WHERE
multimarket.productos.id_order = naviones_db16.ps_orders.id_order
)
ORDER BY
naviones_db16.ps_orders.id_order DESC
This is that i have done in query builder
$naviones = DB::connection('naviones')->table('ps_orders')
->select('ps_orders.payment', 'ps_orders.total_paid AS total', 'ps_orders.current_state AS current_state', 'ps_orders.id_order AS id_order',
'ps_shop.NAME AS name_shop', 'ps_customer.firstname AS customer_firstname', 'ps_customer.lastname AS customer_lastname', 'ps_orders.reference',
'ps_orders.date_add AS fecha')
->join('ps_customer', 'ps_customer.id_customer', '=', 'ps_orders.id_customer')
->join('ps_shop', 'ps_shop.id_shop', '=', 'ps_orders.id_shop')
->where('ps_orders.current_state', '=', '16')
->orderBy('id_order', 'DESC')
->get()->toArray();
Of course, i have other conection this is: DB::connections('multimarket') but this point i dont have any idea how i could do that. Do you have any idea?
Thank u
I'm getting this error:
Msg 245, Level 16, State 1, Line 10
Conversion failed when converting the nvarchar value 'PLANT001' to data type int
I tried adding convert and cast as int to the first line that's getting the error as well as the last join but I still get the error.
SELECT
hh.PlantID AS 'Plant ID',
hh.ERP AS 'ERP',
hh.ShipViaID AS 'Ship Via ID',
cc.carrier AS 'Carrier',
cc.service AS 'Service',
cc.packagetype AS 'Pkg Type',
hd.HandlingChargeTypeID AS 'Handling Charge ID',
hd.HandlingCharge 'Handling Charge',
hr.AdditionalPercentageAdded 'Heading Addl % Added',
hd.ApplyToEachPackage AS 'Apply to Each Pkg',
hr.MinimumHandlingCharge AS 'Min Handling Charge',
hr.MaximumHandlingCharge AS 'Max Handling Charge'
FROM
HandlingChargeHeader hh
JOIN
HandlingChargeDetails hd ON hd.HandlingChargeHeaderID = hh.ID
JOIN
HandlingChargeRequirements hr ON hh.ID = hr.HandlingChargeHeaderID
LEFT JOIN
xcarrier_codes cc ON cc.ID = hh.ShipViaID AND hh.PlantID = cc.plantid
cc.plantid = nvarchar, hh.plantid = int
You can use try_convert() :
select . . .
from . . .
on . . and
try_convert(int, cc.plantid) = cc.plantid;
However, this seem doesn't solve your problem you need to convert this all time whenever the data required.
The recommended solution is to change your data model if it is possible with immediate effect.
I have a document of type 'User' as-
{
"id":"User-1",
"Name": "Kevin",
"Gender":"M",
"Statuses":[
{
"Status":"ONLINE",
"StatusChangedDate":"2017-11-01T17:12:00Z"
},
{
"Status":"OFFLINE",
"StatusChangedDate":"2017-11-02T13:24:00Z"
},
{
"Status":"ONLINE",
"StatusChangedDate":"2017-11-02T14:35:00Z"
},
{
"Status":"OFFLINE",
"StatusChangedDate":"2017-11-02T15:47:00Z"
}.....
],
"type":"User"
}
I need user's information along with his latest status details based on a particular date (or date range).
I am able to achieve this using subquery and Unnest clause.
Select U.Name, U.Gender, S.Status, S.StatusChangedDate
From (Select U1.id, max(U1.StatusChangedDate) as StatusChangedDate
From UserInformation U1
Unnest Statuses S1
Where U1.type = 'User'
And U1.StatusChangedDate between '2017-11-02T08:00:00Z' And '2017-11-02T11:00:00Z'
And U1.Status = 'ONLINE'
Group by U1.id
) A
Join UserInformation U On Keys A.id
Unnest U.Statuses S
Where U.StatusChangedDate = A.StatusChangedDate;
But is there any other way of achieving this (like by using collection operators and array functions)??
If yes, please provide me a query or guide me through it.
Thanks.
MAX, MIN argument allows array. 0th element of array can be field needs aggregate and 1st element is what you want to carry.
Using this techinuqe you can project non aggregtae field for MIN/MAX like below.
SELECT U.Name, U.Gender, S.Status, S.StatusChangedDate
FROM UserInformation U1
UNNEST Statuses S1
WHERE U1.type = 'User'
AND S1.StatusChangedDate BETWEEN '2017-11-02T08:00:00Z' AND '2017-11-02T11:00:00Z'
AND S1.Status = 'ONLINE'
GROUP BY U1.id
LETTING S = MAX([S1.StatusChangedDate,S1])[1];
In 4.6.3+ you can also try this without UNNEST Using subquery expressions https://developer.couchbase.com/documentation/server/current/n1ql/n1ql-language-reference/subqueries.html . Array indexing query will be faster.
CREATE INDEX ix1 ON UserInformation(ARRAY v FOR v IN Statuses WHEN v.Status = 'ONLINE' END) WHERE type = "User";
SELECT U.Name, U.Gender, S.Status, S.StatusChangedDate
FROM UserInformation U1
LET S = (SELECT RAW MAX([S1.StatusChangedDate,S1])[1]
FROM U1.Statuses AS S1
WHERE S1.StatusChangedDate BETWEEN '2017-11-02T08:00:00Z' AND '2017-11-02T11:00:00Z' AND S1.Status = 'ONLINE')[0]
WHERE U1.type = 'User'
AND ANY v IN U1.Statuses SATISFIES
v.StatusChangedDate BETWEEN '2017-11-02T08:00:00Z' AND '2017-11-02T11:00:00Z' AND v.Status = 'ONLINE' END;
I have this raw sql that I am trying to run on grails
final session = sessionFactory.currentSession;
final String query = 'select count(A.*) from Artifact as A LEFT JOIN classification as C on (A.id=C.artifact_id) where C.id IS NULL OR C.active=0';
final sqlQuery = session.createSQLQuery(query);
def totalunclass = sqlQuery.with {
addEntity(Artifact);
}
But I am getting the error Message: SQL queries do not currently support returning aliases
I tried another method but failed there too achieve the result click here
Try changing your query line to look like this
final String query = 'select count(*) from Artifact A LEFT JOIN classification C on (A.id=C.artifact_id) where C.id IS NULL OR C.active=0';
Try this and remove aliases:
final session = sessionFactory.currentSession;
final String query = 'select count(Artifact.*) from Artifact LEFT JOIN classification on (Artifact.id=classification.artifact_id) where classification.id IS NULL OR classification.active=0';
final sqlQuery = session.createSQLQuery(query);
def totalunclass = sqlQuery.with {
addEntity(Artifact);
}