Laravel 4.2 execute query without using elequent query builder - sql

I have a query with sub-query .. and i want to write an explicite SQL request and execute it
Query :
select count(*) as count from
(
SELECT DISTINCT t.article_id FROM
`articles` as a left join `tags` as t
on a.`id` = t.`article_id`
where a.`flag` = 1
) as sub
i tried this to execute the request without building the query :
DB::connection()->getPdo()->exec( $sql );
But it always return 0 !

You can use sub query with DB::raw.
A method DB::raw() (don’t forget to use Illuminate\Support\Facades\DB) allows you to select whatever you want and basically write raw SQL statements.
DB::select(DB::raw("select count(*) as count from
(
SELECT DISTINCT t.article_id FROM
`articles` as a left join `tags` as t
on a.`id` = t.`article_id`
where a.`flag` = 1
) as sub"));
https://laravel.com/docs/4.2/queries#raw-expressions

Why don't you try with DB::raw('your sql query here')

Using DB::select should solve your problem.
DB::select('select count(*) as count from
(
SELECT DISTINCT t.article_id FROM
`articles` as a left join `tags` as t
on a.`id` = t.`article_id`
where a.`flag` = 1
) as sub');

Related

Why is my query inserting the same values when I have added a 'not exists' parameter that should avoid this from happening?

My query should stop inserting values, as the not exists statement is satisfied (I have checked both tables) and matching incidents exist in both tables, any ideas why values are still being returned?
Here is the code:
INSERT INTO
odwh_system.ead_incident_credit_control_s
(
incident
)
SELECT DISTINCT
tp.incident
FROM
odwh_data.ead_incident_status_audit_s ei
INNER JOIN odwh_data.ead_incident_s tp ON ei.incident=tp.incident
WHERE
ei.status = 6
OR
ei.status = 7
AND NOT EXISTS
(
SELECT
true
FROM
odwh_system.ead_incident_credit_control_s ead
WHERE
ead.incident = tp.incident
)
AND EXISTS
(
SELECT
true
FROM
odwh_work.ead_incident_tp_s tp
WHERE
tp.incident = ei.incident
);
dont reuse table aliases
use sane aliases
avoid AND/OR conflicts; prefer IN()
INSERT INTO odwh_system.ead_incident_credit_control_s (incident)
SELECT -- DISTINCT
tp.incident
FROM odwh_data.ead_incident_s dtp
WHERE NOT EXISTS (
SELECT *
FROM odwh_system.ead_incident_credit_control_s sic
WHERE sic.incident = dtp.incident
)
AND EXISTS (
SELECT *
FROM odwh_work.ead_incident_tp_s wtp
JOIN odwh_data.ead_incident_status_audit_s dis ON wtp.incident = dis.incident AND dis.status IN (6 ,7)
WHERE wtp.incident = dtp.incident
);

ERROR SQL Server ONLY one expression can be specified in the select list when the subquery is not introduced with exists

I am trying to run my query but I get an error.
This is my query:
if exists (select CODE_ISIN
from cte
where code_ISIN not in (select [STATUT_TITRE], [CODE_ISIN]
from TT_TITRE A
inner join TT_STATUT_TITRE B on A.TITRE_ID = B.TITRE_ID))
begin
select 'ko'
end
begin
select 'ok'
end
Remove [STATUT_TITRE] from sub-query as it will accept only one expression :
select c.CODE_ISIN
from cte c
where code_ISIN not in (select [CODE_ISIN] -- only one expression needed
from TT_TITRE A inner join
TT_STATUT_TITRE B
on A.TITRE_ID = B.TITRE_ID
);
I would suggest to use NOT EXISTS instead :
where not exists (select 1
from TT_TITRE A inner join
TT_STATUT_TITRE B
on A.TITRE_ID=B.TITRE_ID
where CODE_ISIN = c.CODE_ISIN
);

Rewrite query without using temp table

I have a query that is using a temp table to insert some data then another select from to extract distinct results. That query by it self was fine but now with entity-framework it is causing all kinds of unexpected errors at the wrong time.
Is there any way I can rewrite the query not to use a temp table? When this is converted into a stored procedure and in entity framework the result set is of type int which throws an error:
Could not find an implementation of the query pattern Select not found.
Here is the query
Drop Table IF EXISTS #Temp
SELECT
a.ReceiverID,
a.AntennaID,
a.AntennaName into #Temp
FROM RFIDReceiverAntenna a
full join Station b ON (a.ReceiverID = b.ReceiverID) and (a.AntennaID = b.AntennaID)
where (a.ReceiverID is NULL or b.ReceiverID is NULL)
and (a.AntennaID IS NULL or b.antennaID is NULL)
select distinct r.ReceiverID, r.ReceiverName, r.receiverdescription
from RFIDReceiver r
inner join #Temp t on r.ReceiverID = t.ReceiverID;
No need for anything fancy, you can just replace the reference to #temp with an inner sub-query containing the query that generates #temp e.g.
select distinct r.ReceiverID, r.ReceiverName, r.receiverdescription
from RFIDReceiver r
inner join (
select
a.ReceiverID,
a.AntennaID,
a.AntennaName
from RFIDReceiverAntenna a
full join Station b ON (a.ReceiverID = b.ReceiverID) and (a.AntennaID = b.AntennaID)
where (a.ReceiverID is NULL or b.ReceiverID is NULL)
and (a.AntennaID IS NULL or b.antennaID is NULL)
) t on r.ReceiverID = t.ReceiverID;
PS: I haven't made any effort to improve the query overall like Gordon has but do consider his suggestions.
First, a full join makes no sense in the first query. You are selecting only columns from the first table, so you need that.
Second, you can use a CTE.
Third, you should be able to get rid of the SELECT DISTINCT by using an EXISTS condition.
I would suggest:
WITH ra AS (
SELECT ra.*
FROM RFIDReceiverAntenna ra
Station s
ON s.ReceiverID = ra.ReceiverID AND
s.AntennaID = ra.AntennaID)
WHERE s.ReceiverID is NULL
)
SELECT r.ReceiverID, r.ReceiverName, r.receiverdescription
FROM RFIDReceiver r
WHERE EXISTS (SELECT 1
FROM ra
WHERE r.ReceiverID = ra.ReceiverID
);
You can use CTE instead of the temp table:
WITH
CTE
AS
(
SELECT
a.ReceiverID,
a.AntennaID,
a.AntennaName
FROM
RFIDReceiverAntenna a
full join Station b
ON (a.ReceiverID = b.ReceiverID)
and (a.AntennaID = b.AntennaID)
where
(a.ReceiverID is NULL or b.ReceiverID is NULL)
and (a.AntennaID IS NULL or b.antennaID is NULL)
)
select distinct
r.ReceiverID, r.ReceiverName, r.receiverdescription
from
RFIDReceiver r
inner join CTE t on r.ReceiverID = t.ReceiverID
;
This query will return the same results as your original query with the temp table, but its performance may be quite different; not necessarily slower, it can be faster. Just something that you should be aware about.

select query with Not IN keyword

I have two Tables as below..
tbPatientEncounter
tbVoucher
when i execute select query as below
Select EncounterIDP,EncounterNumber from tbPatientEncounter
it returens me 180 rows. and
Select VoucherIDP,EncounterIDF from tbVoucher
above query returns me 165 rows.
but i want to execute select query that returns me data like EncounterIDP not in tbVoucher, for that i have tried below Select query...
Select * from tbPatientEncounter pe
where pe.EncounterIDP not in
(Select v.EncounterIDF from tbVoucher v )
it doesn't returns any row. in first image it shows EncounterIDP 9 in tbPatientEncounter, but it not inserted in tbVoucher for that i have tried select Query like
Select * from tbVoucher where EncounterIDF = 9
it returns me 0 rows.
My question is what is wrong with my above Not In Query.?
In all likelihood, the problem is NULL values in tbVoucher. Try this:
Select *
from tbPatientEncounter pe
where pe.EncounterIDP not in (Select v.EncounterIDF
from tbVoucher v
where v.EncounterIDF is not NULL
)
Are you comparing the correct fields in tbVoucher?
Try using a left join
Select EncounterIDP,EncounterNumber from tbPatientEncounter
left join tbVoucher on EncounterIDP = EncounterIDF
where EncounterIDF is null
Call me a skeptic because I don't see anything wrong with your query. Is this really all in the query or did you simplify it for us?
Select * from tbPatientEncounter pe
where pe.EncounterIDP not in
(Select v.EncounterIDF from tbVoucher v )

SQL WHERE In a many-to-many or many-to-many empty

Does anyone know a way to simplify this WHERE expression?
WHERE (
(#UserSpecialtyID in
(
SELECT CharacteristicSpecialties_Id
FROM ModalityVariantSpecialty
WHERE ModalityVariants_Id = ModalityVariants.Id
)
)
OR
NOT EXISTS
(
SELECT CharacteristicSpecialties_Id
FROM ModalityVariantSpecialty
WHERE ModalityVariants_Id = ModalityVariants.Id
)
)
Something like this should probably work but Im not exactly clear on the relationships for your tables. I could probably give a better example if you could explain the relationships.
SELECT
*
FROM MadalityVariants mv
LEFT JOIN ModalityVariantSpecialty mvs on mvs.ModalityVariants_ID = mv.ID
WHERE
#UserSpecialtyID = mvs.CharacteristicSpecialties_ID
OR
mvs.CharacteristicSpecialties_ID is null
WHERE (
#UserSpecialtyID in
(
SELECT COALESCE(CharacteristicSpecialties_Id, A.A)
FROM (SELECT #UserSpecialtyID A) A LEFT JOIN ModalityVariantSpecialty
ON ModalityVariants_Id = ModalityVariants.Id
)
)
this works well if CharacteristicSpecialties_Id is a NON NULLABLE field.
I am assuming that this is a WHERE clause of a SELECT on the table ModalityVariants
Would this work (The SQL is not tested)?
SELECT *
FROM ModalityVariants
LEFT OUTER JOIN ModalityVariantSpeciality
ON ModalityVariants.Id = ModalityVariants_ID
WHERE CharacteristicSpecialities_Id = #UserSpecialityID or
CharacteristicSpecialities_Id is NULL
Here's my attempt:
WHERE #UserSpecialtyID = COALESCE
(
SELECT TOP 1 CharacteristicSpecialties_Id
FROM ModalityVariantSpecialty
WHERE ModalityVariants_Id = ModalityVariants.Id
ORDER BY
CASE WHEN CharacteristicSpecialties_Id = UserSpecialtyID THEN 1
ELSE 2 END ASC
), #UserSpecialtyID)
If both ModalityVariants_Id and UserSpecialtyID match, the subquery returns CharacteristicSpecialties_Id, and the where succeeds
If only ModalityVariants_Id matches, the subquery returns a different ID, and the where fails
If neither matches, the subquery returns NULL, the COALESCE returns #UserSpecialtyID, and the where succeeds
Probably clearest is a variety of John Hartsock's answer, with a subquery to ensure the left join doesn't add any rows.
select *
from ModalityVariants mv
left join
(
select distinct ModalityVariants_ID
, CharacteristicSpecialties_ID
from ModalityVariantSpecialty
) as mvs
on mvs.ModalityVariants_ID = mv.ID
where #UserSpecialtyID = mvs.CharacteristicSpecialties_ID
OR
mvs.CharacteristicSpecialties_ID is null
I'll vote for John's answer :)