I have an application where a lot of options can be selected where there are four tables and possible 4 different terms from each filter and also additional for if we take value count and i am no good with queries just know how to get the desired result.So the queries can be like:
select distinct(maindbgroupid) from ((SELECT mainDBGroupID from
groupstatisticsdata.seniority where ( `name` = 'Senior' )AND maindbgroupid in (SELECT
mainDBGroupID from groupstatisticsdata.Function where ( `name` = 'Information Technology'
)AND (`Value` >1000) AND maindbgroupid in (SELECT mainDBGroupID from
groupstatisticsdata.Industry where ( `name` = 'Information Technology and Services' )AND
(`Value` >1000))))) t join maingroupdb.campaigns on campaigns.groupid=t.maindbgroupid
where campaigns.campaignName='Campaign1101'
This is one example , how to improve it please as i always get timeout when i use more than one filter.
What i am doing in the query is an intersect between the tables.
Try this ::
select distinct(mainDBGroupID)
from
groupstatisticsdata.seniority
inner join groupstatisticsdata.Function on (groupstatisticsdata.seniority.maindbgroupid=groupstatisticsdata.Function.mainDBGroupID)
inner join groupstatisticsdata.Industry on (groupstatisticsdata.Industry.mainDBGroupID=groupstatisticsdata.seniority.maindbgroupid)
inner join maingroupdb.campaigns on campaigns.groupid=t.maindbgroupid
where groupstatisticsdata.seniority.`name` = 'Senior' AND
groupstatisticsdata.Function.`name` = 'Information Technology'
AND `Value` >1000
AND maindbgroupid
AND groupstatisticsdata.Industry.`name` = 'Information Technology and Services' )
AND
groupstatisticsdata.Industry.`Value` >1000
AND campaigns.campaignName='Campaign1101'
Related
I've a SELECT which checks a status of active alarms (icinga).
This select joins different tables and until here all ok.
On the result I've as value/column an object_id as well. I would like to add a column to that select that could be empty or not, because, searching that 'object_id' on a different table, I could get a value or not. This accessory table is structured having: object_id, varname, varvalue.
So, i.e., my SELECT returns those values:
`name`, `object_id`, `status`
`Hello`, `123456`, `OK`
I would add the column City that should compared to a table having:
`object_id`, `varname`, `varvalue`
`123456`, `city`, `Rome`
`123456`, `lake`, `Garda`
`789789`, `city`, `Milano`
So that if the second table has object_id = 123456 AND city = Rome the result should be:
`name`, `object_id`, `status`, `city`
`Hello`, `123456`, `OK`, `Rome`
Otherwise the result should be:
`Hello`, `123456`, `OK`, `UNKNOWN`
How to do that?
Hope I've explained it well :-)
Thanks!
* EDIT *
It's better I explain with real example. My query actually is the following:
select icinga_objects.object_id, icinga_objects.name1 as host_name, icinga_objects.name2 as ServiceName, "service" as Type, icinga_servicestatus.last_check as LastCheckTime, icinga_servicestatus.last_hard_state_change as LastStateChange, TIMEDIFF(now(), icinga_servicestatus.last_hard_state_change) AS SinceTime,
CASE
WHEN icinga_servicestatus.current_state = 0 THEN '0'
WHEN icinga_servicestatus.current_state = 1 THEN '2'
WHEN icinga_servicestatus.current_state = 2 THEN '3'
ELSE '3'
END AS state
FROM icinga_objects, icinga_servicestatus, icinga_services WHERE icinga_servicestatus.service_object_id IN
(SELECT service_object_id FROM icinga_services WHERE icinga_services.host_object_id IN
(SELECT host_object_id FROM icinga_hostgroup_members WHERE hostgroup_id IN
(SELECT hostgroup_id FROM icinga_hostgroups WHERE alias = 'MY-HOSTGROUP-TO-FILTER')
)
)
AND icinga_servicestatus.service_object_id NOT IN
(SELECT service_object_id FROM icinga_services WHERE icinga_services.service_object_id IN (
SELECT object_id FROM icinga_objects WHERE icinga_objects.is_active = 1 AND icinga_objects.object_id IN
(SELECT object_id FROM icinga_customvariables WHERE varvalue = '8x5')
)
)
AND icinga_servicestatus.last_check > NOW() - INTERVAL 3 HOUR
AND icinga_servicestatus.state_type = 1
AND icinga_servicestatus.scheduled_downtime_depth = 0
AND icinga_objects.object_id = icinga_services.service_object_id
AND icinga_servicestatus.service_object_id = icinga_services.service_object_id
AND icinga_servicestatus.current_state = 2
AND icinga_servicestatus.problem_has_been_acknowledged = 0
This gives me as result, in example:
`object_id`, `host_name`, `ServiceName`, `Type`, `LastCheckTime`, `LastStateChange`, `SinceTime`, `State`
`123456`, `myHostName`, `myServiceName`, `service`, `2020-04-29 17:19:21`, `2020-04-28 14:50:27`, `26:32:51`, `3`
Here I would like to add the column.
So, now if I search object_id into icinga_customvariables I could find entries, or not. In Example, searching object_id = 123456 I have 4 records, but ONLY one having varname = NAME_IM_SEARCHING and so I need to add to the above result the corresponding of varvalue searching icinga_customvariables.object_id = '123456' AND varname = NAME_IM_SEARCHING. IF there are NO results, then the added cloumn should be UNKNOWN, otherwise the added column should be = icinga_customvariables.varvalue.
How to add it? :-)
You can place your query into a "table expression" so it becomes simpler to join it to the other_table. For example:
select
q.*,
coalesce(o.varvalue, 'UNKNOWN') as city
from (
-- your existing query here
) q
left join other_table o on o.object_id = q.object_id and o.varname = 'city'
EDIT: Joining multiple times
As requested if you need to extract more city names using another column, or if you want to extract against another table altogether, you can add an extra LEFT JOIN. For example:
select
q.*,
coalesce(o.varvalue, 'UNKNOWN') as city,
coalesce(o2.varvalue, 'UNKNOWN') as lake
from (
-- your existing query here
) q
left join other_table o on o.object_id = q.object_id and o.varname = 'city'
left join other_table o2 on o.object_id = q.object_id and o2.varname = 'lake'
Hello, I have two tables and one junction table. And I want to find all estates, that has one or multiple comforts. I wrote this query (postrgreSql):
SELECT DISTINCT "estates".*
FROM "estates"
LEFT JOIN "estate_comforts"
ON "estates"."id" = "estate_comforts"."estate_id"
WHERE "estate_comforts"."comfort_id" IN ( '1', '2' )
It finding estates that has the first comfort OR the second, but I need to search in "AND" mode.
This project using Yii2 framewors, so plain sql or ActiveRecord statement are acceptable.
Update. This query select all esates, regardless of the comforts
SELECT DISTINCT "estates".*
FROM "estates"
LEFT JOIN "estate_comforts"
ON "estates"."id" = "estate_comforts"."estate_id"
AND "estate_comforts"."comfort_id" IN ( '1', '2' )
Either JOIN estate_comforts twice, one time for comfort_id 1, and another time for comfort_id 2:
SELECT DISTINCT "estates".*
FROM "estates"
INNER JOIN "estate_comforts" ec1
ON "estates"."id" = ec1."estate_id"
INNER JOIN "estate_comforts" ec2
ON "estates"."id" = ec2."estate_id"
WHERE ec1."comfort_id" = '1'
AND ec2."comfort_id" = '2'
Alternatively, do a GROUP BY on estate_comforts to find estate_id with at least two different comfort_id values. Join with that result:
select e.*
from "estates" e
join (select "estate_id"
from "estate_comforts"
WHERE "comfort_id" IN ( '1', '2' )
group by "estate_id"
having count(distinct "comfort_id") >= 2) ec ON e."id" = ec."estate_id"
I hope you can get me here. I'm working on a PMS system and I want to run a simple SELECT statement to get a list of secret codes for my customers based on which of their parcels have arrived and the transaction type. The 'transferConfirmation' table already has the customer ID and the secret code and displays one row for each instance but for some reason, when i use the following query:
SELECT `tc`.`transferID` AS `transferID`,
`c`.`firstName` AS `firstName`,
`c`.`lastName` AS `lastName`,
`tc`.`secretCode` AS `secretCode`,
'Purchase Order' AS `transactionType`
FROM (((((`db`.`transferconfirmation` `tc`
JOIN `db`.`customer` `c` on((`tc`.`customerID` = `c`.`customerID`)))
JOIN `db`.`transfer` `t` on((`t`.`transferID` = `tc`.`transferID`)))
JOIN `db`.`transferentry` `te` on((`t`.`transferID` = `te`.`transferID`)))
JOIN `db`.`purchaseorder` `po` on((`te`.`referenceID` = `po`.`purchaseOrderID`)))
JOIN `db`.`purchaseorderentry` `poe` on(((`po`.`purchaseOrderID` = `poe`.`purchaseOrderID`)
AND (`te`.`referenceEntryID` = `poe`.`purchaseOrderEntryID`))))
WHERE (`poe`.`collectionStatus` = 0)
UNION ALL
SELECT `tc`.`transferID` AS `transferID`,
`c`.`firstName` AS `firstName`,
`c`.`lastName` AS `lastName`,
`tc`.`secretCode` AS `secretCode`,
'Shipping Order' AS `transactionType`
FROM (((((`db`.`transferconfirmation` `tc`
JOIN `db`.`customer` `c` on((`tc`.`customerID` = `c`.`customerID`)))
JOIN `db`.`transfer` `t` on((`t`.`transferID` = `tc`.`transferID`)))
JOIN `db`.`transferentry` `te` on((`t`.`transferID` = `te`.`transferID`)))
JOIN `db`.`shippingorder` `so` on((`te`.`referenceID` = `so`.`shippingOrderID`)))
JOIN `db`.`shippingorderentry` `soe` on(((`so`.`shippingOrderID` = `soe`.`shippingOrderID`)
AND (`te`.`referenceEntryID` = `soe`.`shippingOrderEntryID`))))
WHERE (`soe`.`collectionstatus` = 0)
I keep getting results with duplicate data only difference is with the transaction. I guess my question is, if the secret code has been selected once, how to I prevent any other row from displaying the same code.
Use the UNION operator. The UNION operator will remove duplicate records from each query (UNION ALL would retain them).
SELECT transferID, firstName, lastName, secretCode,
'Purchase Order' AS transactionType
FROM ...
UNION
SELECT transferID, firstName, lastName, secretCode,
'Purchase Order' AS transactionType
FROM ...
I got 2 tables tbl_issued and tbl_transaction.
tbl_issued has its columns, ItemID,Item,Serial,Quantity and Size. While tbl_transaction has its columns Released,Received,Approved and Department
My problem is I want to get their columns in 1 query, this is mysql query
SELECT `ItemID`,`Item`,`Serial`,`Quantity`,`Size`,`Class`,`Unit`,(SELECT `Released` FROM `tbl_transaction` WHERE `TransactionID` = 12458952) AS `Released`,
(SELECT `Received` FROM `tbl_transaction` WHERE `TransactionID` = 12458952) AS `Received`,
(SELECT `Approved` FROM `tbl_transaction` WHERE `TransactionID` = 12458952) AS `Aprroved`,
(SELECT `Department` FROM `tbl_transaction` WHERE `TransactionID` = 12458952) AS `Department`
FROM `tbl_issued` WHERE `TransactionID` = 12458952
but transferring this on vb.net does not provide output.
Any ideas how i will translate this query to vb.net? Thanks in advance for help!
I don't know what you are trying to do but if you want it to be simplified, here's how. Have you tried Inner Joins? It's like this.
SELECT ItemID, Item, Serial, Quantity, Size, Class, Unit, Released, Received,
Approved, Deparment from tbl_issued a INNER JOIN tbl_transaction b on
a.TransactionID = b.TransactionID Where a.TransactionID = 12458952
I assume that both tables have TransactionID based on your query.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
SQL query help - have two where conditons in join condition
I have the following tables with the columns as below. I have mentioned what I need from this. I already posted a link in here SQL query help - have two where conditons in join condition with what I have been trying but cannot get this through. Once again positing it plainly with what I need:
Book
BookId, BookName
Desk
DeskId, BookId ,DeskName
CounterParty
CPId, CpName
Trade
TradeId, Buyer, Seller
This is how the Buyer and Seller data would be :
Buyer Seller
B3232 B323
C32 B222
B323 C323
Based on the starting character B or C in these two columns, I need to join Book or CP table to check the ids.
I need **t.TradingDeskName, b.BookName, c.CpName, t.Buyer, t.Seller.**
Any help is very much appreciated.
Thanks,
mani
p.s : I am trying to get this done through SQL or Linq to Sql.
The recent query but have more to fix :
SELECT DISTINCT desk.Name as TradingDeskName, b.Name as Book, t.Seller, t.Buyer, c.PartyName, FROM TradingDesk AS desk
RIGHT JOIN Book as b
ON b.TradingDeskId = d.Id
RIGHT JOIN Trade as t
ON LEFT(t.Buyer, 1) = 'B' AND SUBSTRING(t.Buyer, 2, len(t.Buyer)) = b.Id
LEFT JOIN Book as b1
ON LEFT(t.Seller, 1) = 'B' AND SUBSTRING(t.Seller, 2, len(t.Seller)) = b1.Id
LEFT JOIN CounterParty as c
ON LEFT(t.Buyer, 1) = 'C' AND SUBSTRING(t.Buyer, 2, len(t.Buyer)) = c.PartyId
LEFT JOIN CounterParty as c1
ON LEFT(t.Seller, 1) = 'C' AND SUBSTRING(t.Seller, 2, len(t.Seller)) = c1.PartyId
As I mentioned I need :
Desk.Name - B.Name - T.Seller - T.Buyer- C.PartyName
The C.PartyName will have the value if T.Seller or T.Buyer value is starting with 'C' (from CounterParty Table) else will be null.
With the above query, I have null values coming in Desk.Name, B.Name and the logic of gettig C.PartyName is also not working.
There are a couple ways I could think of for achieving the desired results but because first things should come first, I'd suggest to modify the DB design if it is at all possible.
So, here are the 2 queries that I could work out:
Query 1
SELECT `t`.*,
(CASE
WHEN LEFT(`t`.`Buyer`, 1) = 'B' THEN
(SELECT `b`.`BookName`
FROM `Book` `b`
WHERE `b`.`BookId` = SUBSTRING(`t`.`Buyer`, 2))
ELSE (SELECT `c`.`CPName`
FROM `CounterParty` `c`
WHERE `c`.`CPId` = SUBSTRING(`t`.`Buyer`, 2))
END) AS `buyer_name`,
(CASE
WHEN LEFT(`t`.`Seller`, 1) = 'B' THEN
(SELECT `b`.`BookName`
FROM `Book` `b`
WHERE `b`.`BookId` = SUBSTRING(`t`.`Seller`, 2))
ELSE (SELECT `c`.`CPName`
FROM `CounterParty` `c`
WHERE `c`.`CPId` = SUBSTRING(`t`.`Seller`, 2))
END) AS `seller_name`
FROM `Trade` `t`
Query 2
SELECT *
FROM `Trade` `t`
LEFT JOIN `Book` `b` ON LEFT(`t`.`Buyer`, 1) = 'B' AND SUBSTRING(`t`.`Buyer`, 2) = `b`.`BookId`
LEFT JOIN `Book` `b1` ON LEFT(`t`.`Seller`, 1) = 'B' AND SUBSTRING(`t`.`Seller`, 2) = `b1`.`BookId`
LEFT JOIN `CounterParty` `c` ON LEFT(`t`.`Buyer`, 1) = 'C' AND SUBSTRING(`t`.`Buyer`, 2) = `c`.`CPId`
LEFT JOIN `CounterParty` `c1` ON LEFT(`t`.`Seller`, 1) = 'C' AND SUBSTRING(`t`.`Seller`, 2) = `c1`.`CPId`;
Both the above queries return same results but in different formats. Please try and see which one works best for you.
Also, it isn't very clear from your question where does the table Desk fit in and what relations does it hold with other tables. Please feel free to add respective columns you'll need from Desk.
Please note that the suggested queries are in MySQL. It is not very clear what system are you running - you've mentioned in your post that you are trying using SQL or Linq SQL and in the tags you've mentioned everything + MySQL.
You could do it something like this (untested):
select
t.Buyer,
t.Seller,
case when t.Buyer like 'B%' THEN (select BookName from Book where BookId = t.Buyer)
ELSE (select CpName from Counterparty where CPId = t.Buyer)
end BuyerName,
case when t.Buyer like 'B%' THEN (select DeskName from Desk where BookId = t.Buyer)
ELSE NULL
end BuyerDeskName,
case when t.Seller like 'B%' THEN (select BookName from Book where BookId = t.Seller)
ELSE (select CpName from Counterparty where CPId = t.Seller)
end SellerName,
case when t.Seller like 'B%' THEN (select DeskName from Desk where BookId = t.Seller)
ELSE NULL
end SellerDeskName,
from
Trade t
The problem you have is that, since the table you want to join to is data driven, you can't specify it in the FROM clause..