Search Results

Search found 323 results on 13 pages for 'in subquery'.

Page 1/13 | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • subquery factoring questions.

    - by Sujee
    Hi, Please explain. a) is "subquery factoring" used to replace a non-correlated subquery? What about correlated subquery? b) if it is true, are "subquery" and "subquery factoring" executed exactly once? c) "subquery" vs "subquery factoring" which one is better Thank you.

    Read the article

  • Write subquery in Criteria of nHibernate.

    - by Bipul
    I read about subquery in Criteria, but I am still unable to grasp it properly. So, here I am taking one example and if somebody can help me writing that using subquery it will be great. Lets say we have table Employee{EmployeeId.(int),Name(string),Post(string),No_Of_years_working(int)} Now I want all the employees who are Managers and working for less than 10 years. I know that we can get the result without using subqueries but I wanna use subquery just to understand how it works in criteria. So, how I can write Criteria using subquery to get those employees. Thanks

    Read the article

  • IP address numbers in MySQL subquery

    - by Iain Collins
    I have a problem with a subquery involving IPV4 addresses stored in MySQL (MySQL 5.0). The IP addresses are stored in two tables, both in network number format - e.g. the format output by MySQL's INET_ATON(). The first table ('events') contains lots of rows with IP addresses associated with them, the second table ('network_providers') contains a list of provider information for given netblocks. events table (~4,000,000 rows): event_id (int) event_name (varchar) ip_address (unsigned 4 byte int) network_providers table (~60,000 rows): ip_start (unsigned 4 byte int) ip_end (unsigned 4 byte int) provider_name (varchar) Simplified for the purposes of the problem I'm having, the goal is to create an export along the lines of: event_id,event_name,ip_address,provider_name If do a query along the lines of either of the following, I get the result I expect: SELECT provider_name FROM network_providers WHERE INET_ATON('192.168.0.1') >= network_providers.ip_start ORDER BY network_providers.ip_start DESC LIMIT 1 SELECT provider_name FROM network_providers WHERE 3232235521 >= network_providers.ip_start ORDER BY network_providers.ip_start DESC LIMIT 1 That is to say, it returns the correct provider_name for whatever IP I look up (of course I'm not really using 192.168.0.1 in my queries). However, when performing this same query as a subquery, in the following manner, it doesn't yield the result I would expect: SELECT event.id, event.event_name, (SELECT provider_name FROM network_providers WHERE event.ip_address >= network_providers.ip_start ORDER BY network_providers.ip_start DESC LIMIT 1) as provider FROM events Instead the a different (incorrect) value for network_provider is returned - over 90% (but curiously not all) values returned in the provider column contain the wrong provider information for that IP. Using event.ip_address in a subquery just to echo out the value confirms it contains the value I'd expect and that the subquery can parse it. Replacing event.ip_address with an actual network number also works, just using it dynamically in the subquery in this manner that doesn't work for me. I suspect the problem is there is something fundamental and important about subqueries in MySQL that I don't get. I've worked with IP addresses like this in MySQL quite a bit before, but haven't previously done lookups for them using a subquery. The question: I'd really appreciate an example of how I could get the output I want, and if someone here knows, some enlightenment as to why what I'm doing doesn't work so I can avoid making this mistake again. Notes: The actual real-world usage I'm trying to do is considerably more complicated (involving joining two or three tables). This is a simplified version, to avoid overly complicating the question. Additionally, I know I'm not using a between on ip_start & ip_end - that's intentional (the DB's can be out of date, and such cases the owner in the DB is almost always in the next specified range and 'best guess' is fine in this context) however I'm grateful for any suggestions for improvement that relate to the question. Efficiency is always nice, but in this case absolutely not essential - any help appreciated.

    Read the article

  • Are Conditional subquery

    - by Tobias Schulte
    I have a table foo and a table bar, where each foo might have a bar (and a bar might belong to multiple foos). Now I need to select all foos with a bar. My sql looks like this SELECT * FROM foo f WHERE [...] AND ($param IS NULL OR (SELECT ((COUNT(*))>0) FROM bar b WHERE f.bar = b.id)) with $param being replaced at runtime. The question is: Will the subquery be executed even if param is null, or will the dbms optimize the subquery out?

    Read the article

  • predicate subquery to return items by matching tags

    - by user3411663
    I have a many-to-many relationship between two entities; Item and Tag. I'm trying to create a predicate to take the selectedItem and return a ranking of items based on how many similar tags they have. So far I've tried: NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SUBQUERY(itemToTag, $item, $item in %@).@count > 0", selectedItem.itemToTag]; Any other iterations that have failed. It currently only returns the selectedItem in the list. I've found little on Subquery. Is there a guru out there that can help me refine this? Thanks in advance for the help!

    Read the article

  • MYSQL, Subquery Reference in Union

    - by christian
    Is there any way to reference a subquery in a union? I am trying to do something like the following, and would like to avoid a temporary table, but the subquery will be drawn from a much larger dataset so it makes sense to only do it once.. SELECT * FROM (SELECT * FROM ads WHERE state='FL' AND city='Maitland' AND page='home' ORDER BY RAND()) AS sq WHERE spot = 'full-banner' LIMIT 1 UNION SELECT * FROM sq WHERE spot = 'leaderboard' LIMIT 1 UNION SELECT * FROM sq WHERE spot = 'rectangle1' LIMIT 1 UNION SELECT * FROM sq WHERE spot = 'rectangle2' LIMIT 1 .... etc,, It's a shame that DISTINCT can't be specified for a single column of a result set.

    Read the article

  • NHibernate - joining on a subquery using ICriteria

    - by owensymes.mp
    I have a SQL query that I need to represent using NHibernate's ICriteria API. SELECT u.Id as Id, u.Login as Login, u.FirstName as FirstName, u.LastName as LastName, gm.UserGroupId_FK as UserGroupId, inner.Data1, inner.Data2, inner.Data3 FROM dbo.User u inner join dbo.GroupMember gm on u.Id = gm.UserAnchorId_FK left join ( SELECT di.UserAnchorId_FK, sum(di.Data1) as Data1, sum(di.Data2) as Data2, sum(di.Data3) as Data3 FROM dbo.DailyInfo di WHERE di.Date between '2009-04-01' and '2009-06-01' GROUP BY di.UserAnchorId_FK ) inner ON inner.UserAnchorId_FK = u.Id WHERE gm.UserGroupId_FK = 195 Attempts so far have included mapping 'User' and 'DailyInfo' classes (my entities) and making a DailyInfo object a property of the User object. However, how to map the foreign key relationship between them is still a mystery, ie <one-to-one></one-to-one> <one-to-many></one-to-many> <generator class="foreign"><param name="property">Id</param></generator> (!) Solutions on the web are generally to do with subqueries within a WHERE clause, however I need to left join on this subquery instead to ensure NULL values are returned for rows that do not join. I have the feeling that I should be using a Criteria for the outer query, then forming a 'join' with a DetachedCriteria to represent the subquery?

    Read the article

  • Using outer query result in a subquery in postgresql

    - by brad
    I have two tables points and contacts and I'm trying to get the average points.score per contact grouped on a monthly basis. Note that points and contacts aren't related, I just want the sum of points created in a month divided by the number of contacts that existed in that month. So, I need to sum points grouped by the created_at month, and I need to take the count of contacts FOR THAT MONTH ONLY. It's that last part that's tricking me up. I'm not sure how I can use a column from an outer query in the subquery. I tried something like this: SELECT SUM(score) AS points_sum, EXTRACT(month FROM created_at) AS month, date_trunc('MONTH', created_at) + INTERVAL '1 month' AS next_month, (SELECT COUNT(id) FROM contacts WHERE contacts.created_at <= next_month) as contact_count FROM points GROUP BY month, next_month ORDER BY month So, I'm extracting the actual month that my points are being summed, and at the same time, getting the beginning of the next_month so that I can say "Get me the count of contacts where their created at is < next_month" But it complains that column next_month doesn't exist This is understandable as the subquery knows nothing about the outer query. Qualifying with points.next_month doesn't work either. So can someone point me in the right direction of how to achieve this? Tables: Points score | created_at 10 | "2011-11-15 21:44:00.363423" 11 | "2011-10-15 21:44:00.69667" 12 | "2011-09-15 21:44:00.773289" 13 | "2011-08-15 21:44:00.848838" 14 | "2011-07-15 21:44:00.924152" Contacts id | created_at 6 | "2011-07-15 21:43:17.534777" 5 | "2011-08-15 21:43:17.520828" 4 | "2011-09-15 21:43:17.506452" 3 | "2011-10-15 21:43:17.491848" 1 | "2011-11-15 21:42:54.759225" sum, month and next_month (without the subselect) sum | month | next_month 14 | 7 | "2011-08-01 00:00:00" 13 | 8 | "2011-09-01 00:00:00" 12 | 9 | "2011-10-01 00:00:00" 11 | 10 | "2011-11-01 00:00:00" 10 | 11 | "2011-12-01 00:00:00"

    Read the article

  • TSQL - TOP X in FROM Subquery?

    - by EWizard
    Can someone please enlighten me to a way to filter a subquery that is located in a FROM clause? I would like it to look something like this: SELECT * FROM TABLE_A LEFT JOIN (TOP 8 TABLE_B ) ON TABLE_B.id = TABLE_A.id

    Read the article

  • T-sql Common expression query as subquery

    - by ase69s
    I have the following query: WITH Orders(Id) AS ( SELECT DISTINCT anfrageid FROM MPHotlineAnfrageAnhang ) SELECT Id, ( SELECT CONVERT(VARCHAR(255),anfragetext) + ' | ' FROM MPHotlineAnfrageAnhang WHERE anfrageid = Id ORDER BY anfrageid, erstelltam FOR XML PATH('') ) AS Descriptions FROM Orders Its concatenates varchar values of diferents rows grouped by an id. But now i want to include it as a subquery and it gives some errors i cant solve. Simplified example of use: select descriptions from ( WITH Orders(Id) AS ( SELECT DISTINCT anfrageid FROM MPHotlineAnfrageAnhang ) SELECT Id, ( SELECT CONVERT(VARCHAR(255),anfragetext) + ' | ' FROM MPHotlineAnfrageAnhang WHERE anfrageid = Id ORDER BY anfrageid, erstelltam FOR XML PATH('') ) AS Descriptions FROM Orders ) as tx where id=100012 Errors (Aproximate translation from spanish): -Incorrect sintaxis near 'WITH'. -Incorrect sintaxis near 'WITH'. If the instruction is a common table expression or a xmlnamespaces clause, the previous instruction must end with semicolon. -Incorrect sintaxis near ')'. What im doing wrong?

    Read the article

  • SQL Oracle LEFT JOIN and SUBQUERY error: ORA-00905: missing keyword

    - by Curro
    Hello everyone. Asking for your help on this Oracle query. It's giving me the error 2 "ORA-00905: missing keyword". It was working fine before I added the LEFT JOIN statement. Obviously it won't deliver the information as we need it without the LEFT JOIN statement. Please provide any help to know which keyword is missing in this query Thanks a lot!: DB Tables: DW.TICKETS DW.TICKET_ACTLOG Subquery table: TABLE_RESOLVERS SELECT TO_CHAR(DW.TICKETS.RESOLVED_TIMESTAMP,'YYYY-MM-DD HH24:MI:SS') AS RESOLVED_DATE, DW.TICKETS.SUBJECT, DW.TICKETS.OWNER_CORE_ID, DW.TICKETS.TICKET_NUMBER, TABLE_RESOLVERS.SUBMITTER AS RESOLVER_CORE_ID FROM DW.TICKETS LEFT JOIN (SELECT TICKET_NUMBER, SUBMITTER FROM DW.TICKET_ACTLOG WHERE TYPE = 'Final Resolution' AND (SUBMITTER = 'B02666' OR SUBMITTER = 'R66604') ORDER BY CREATE_TIMESTAMP DESC ) AS TABLE_RESOLVERS ON DW.TICKETS.TICKET_NUMBER = TABLE_RESOLVERS.TICKET_NUMBER WHERE DW.TICKETS.RESOLVED_TIMESTAMP >= to_date('05-03-2010','dd-mm-yyyy') AND DW.TICKETS.RESOLVED_TIMESTAMP < to_date('8-03-2010','dd-mm-yyyy') AND DW.TICKETS.TICKET_NUMBER LIKE 'TCK%' AND DW.TICKETS.TICKET_NUMBER IN (SELECT TICKET_NUMBER FROM DW.TICKET_ACTLOG WHERE (SUBMITTER = 'B02666' OR SUBMITTER = 'R66604') ) ORDER BY DW.TICKETS.CREATE_TIMESTAMP ASC

    Read the article

  • Can this MySQL subquery be optimised?

    - by Dan
    I have two tables, news and news_views. Every time an article is viewed, the news id, IP address and date is recorded in news_views. I'm using a query with a subquery to fetch the most viewed titles from news, by getting the total count of views in the last 24 hours for each one. It works fine except that it takes between 5-10 seconds to run, presumably because there's hundreds of thousands of rows in news_views and it has to go through the entire table before it can finish. The query is as follows, is there any way at all it can be improved? SELECT n.title , nv.views FROM news n LEFT JOIN ( SELECT news_id , count( DISTINCT ip ) AS views FROM news_views WHERE datetime >= SUBDATE(now(), INTERVAL 24 HOUR) GROUP BY news_id ) AS nv ON nv.news_id = n.id ORDER BY views DESC LIMIT 15

    Read the article

  • HQL join after output of subquery

    - by user350374
    Hey, Say I have 3 classes class foo1 { List prop1;} class foo2 { foo3 prop2;} class foo3{ int Id;} now I want to select distinct foo2's from foo1 and get Id of foo3. I need to write a HQL stmt for the same. I tried the following select c.Id from (select distinct(a.prop1) from foo1.prop1 as a ) as b inner join b.prop2 as c This throws an 'Antlr.Runtime.NoViableAltException How do you suggest I should go about the same. Please note the inner subquery is working fine. So if I have made some mistakes in there please ignore that. I need a method to do the latter. Thanks in Advance.

    Read the article

  • SQL Server uncorrelated subquery very slow

    - by brianberns
    I have a simple, uncorrelated subquery that performs very poorly on SQL Server. I'm not very experienced at reading execution plans, but it looks like the inner query is being executed once for every row in the outer query, even though the results are the same each time. What can I do to tell SQL Server to execute the inner query only once? The query looks like this: select * from Record record0_ where record0_.RecordTypeFK='c2a0ffa5-d23b-11db-9ea3-000e7f30d6a2' and ( record0_.EntityFK in ( select record1_.EntityFK from Record record1_ join RecordTextValue textvalues2_ on record1_.PK=textvalues2_.RecordFK and textvalues2_.FieldFK = '0d323c22-0ec2-11e0-a148-0018f3dde540' and (textvalues2_.Value like 'O%' escape '~') ) )

    Read the article

  • How can I combine result and subquery for IN comparison (mysql)

    - by user325804
    In order for a school project i need to create the following situation within one mysql query. The situation is as such, that a child's tags and a parent's tags need to be combined into one, and compared to a site's tags, depending on a few extra simple equals to lines. For this to happen I only see the option that the result of a subquery is combined with a sub query within that query, as such: SELECT tag.*, (SELECT group_concat(t1.id, ',', (SELECT group_concat(tag.id) FROM adcampaign INNER JOIN adcampaign_tag ON adcampaign.id = adcampaign_tag.adcampaign_id INNER JOIN tag ON adcampaign_tag.tag_id = tag.id WHERE adcampaign.id = 1)) FROM ad, ad_tag, tag AS t1 WHERE ad.id = ad_tag.ad_id AND ad_tag.tag_id = t1.id AND ad.adcampaign_id = 1 AND ad.agecategory_id = 1 AND ad.adsize_id = 1 AND ad.adtype_id = 1) as tags FROM tag WHERE tag.id IN tags But the IN comparison only returns the first result because now the tags aren't a list but a concanated string. Anyone got any suggestion on this? I really need a way to combine it into one array

    Read the article

  • subquery in join with doctrine dql

    - by Martijn de Munnik
    I want to use DQL to create a query which looks like this in SQL: select e.* from e inner join ( select uuid, max(locale) as locale from e where locale = 'nl_NL' or locale = 'nl' group by uuid ) as e_ on e.uuid = e_.uuid and e.locale = e_.locale I tried to use QueryBuilder to generate the query and subquery. I think they do the right thing by them selves but I can't combine them in the join statement. Does anybody now if this is possible with DQL? I can't use native SQL because I want to return real objects and I don't know for which object this query is run (I only know the base class which have the uuid and locale property). $subQueryBuilder = $this->_em->createQueryBuilder(); $subQueryBuilder ->addSelect('e.uuid, max(e.locale) as locale') ->from($this->_entityName, 'e') ->where($subQueryBuilder->expr()->in('e.locale', $localeCriteria)) ->groupBy('e.uuid'); $queryBuilder = $this->_em->createQueryBuilder(); $queryBuilder ->addSelect('e') ->from($this->_entityName, 'e') ->join('('.$subQueryBuilder.') as', 'e_')->join ->where('e.uuid = e_.uuid') ->andWhere('e.locale = e_.locale');

    Read the article

  • Updating records with their subordinates via CTE or subquery

    - by Mike Jolley
    Let's say I have a table with the following columns: Employees Table employeeID int employeeName varchar(50) managerID int totalOrganization int managerID is referential to employeeID. totalOrganization is currently 0 for all records. I'd like to update totalOrganization on each row to the total number of employees under them. So with the following records: employeeID employeeName managerID totalOrganization 1 John Cruz NULL 0 2 Mark Russell 1 0 3 Alice Johnson 1 0 4 Juan Valdez 3 0 The query should update the totalOrganizations to: employeeID employeeName managerID totalOrganization 1 John Cruz NULL 3 2 Mark Russell 1 0 3 Alice Johnson 1 1 4 Juan Valdez 3 0 I know I can get somewhat of an org. chart using the following CTE: WITH OrgChart (employeeID, employeeName,managerID,level) AS ( SELECT employeeID,employeeName,0 as managerID,0 AS Level FROM Employees WHERE managerID IS NULL UNION ALL SELECT Employees.employeeID,Employees.employeeName,Employees.managerID,Level + 1 FROM Employees INNER JOIN OrgChart ON Employees.managerID = OrgChart.employeeID ) SELECT employeeID,employeeName,managerID, level FROM OrgChart; Is there any way to update the Employees table using a stored procedure rather than building some routine outside of SQL to parse through the data?

    Read the article

  • How to write a subquery using DB

    - by Rita
    SELECT SUM( amount_disbursed ) disbusedamount, (select SUM( loaninstallmentpaid_amount ) FROM ourbank_loan_repayment) paidamount, SUM( amount_disbursed )- (select SUM( loaninstallmentpaid_amount ) FROM ourbank_loan_repayment) differenceamount FROM ourbank_loan_disbursement Any Help would be appreciated

    Read the article

  • how to reuse subquery result in mysql

    - by chris
    I'm doing a statistic job like this: SUM |COND1 |COND2 |... -------------------------- 100 |80 | 70 |... The SUM result is calculated from multiple tables, and the CONDs are subset of that. I wrote a sql like this: select tmp1.id,sum,cond1,cond2 as count from ( select id, count(*) as sum from table_1 group by table1.id) tmp1 left join ( select id, count(*) as cond1 from table1 where condition1 group by table1.id) tmp2 on tmp1.id=tmp2.id left join ( select id, count(*) as cond2 from table1 where condition2 group by table1.id) tmp3 on tmp1.id=tmp3.id the problem is that this is very poor efficiency, it will be better if i could use the result of tmp1, but i don't know how to do that. update: simplified the sql, what i mean is how to reuse the first select result of table_1

    Read the article

  • Need Help with SQL Subquery

    - by Pete Augello
    Hey: I am trying to write a query that will return all orders that only have a Subscription included. It is easy enough to write a query that includes all Orders with Subscriptions, another that includes all orders without a Subscription and then compare them with an unmatched query. But I don't want to have to store Queries in my Access database, I prefer to have it all in my ASP code, and I can't get this to work with just one complex query. Here are samples of what works if I store them: Query1 SELECT tblOrders.OrderID, tblOrderItems.ProductID FROM tblOrders INNER JOIN tblOrderItems ON tblOrders.OrderID = tblOrderItems.OrderID WHERE ((Not ((tblOrderItems.ProductID)=12 And (tblOrderItems.ProductID)<=15))); Query2 SELECT tblOrders.OrderID, tblOrderItems.ProductID FROM tblOrders INNER JOIN tblOrderItems ON tblOrders.OrderID = tblOrderItems.OrderID WHERE ((((tblOrderItems.ProductID)=12 And (tblOrderItems.ProductID)<=15))); Query3 SELECT Query2.OrderID, Query2.ProductID FROM Query2 LEFT JOIN Query1 ON Query2.OrderID = Query1.OrderID WHERE (((Query1.OrderID) Is Null)); So, my question is 'how do I write Query3 so that it doesn't refer to Query1 or Query2?' or, am I missing some other way do do this? Thanks, Pete [email protected]

    Read the article

  • SQL: Join vs. subquery

    - by Col. Shrapnel
    I am an old-school MySQL user and always preferred JOIN over sub-query. But nowadays everyone uses sub-query and I hate it, dunno why. Though I've lack of theoretical knowledge to judge myself if there are any difference. Well, I am curious if sub-query as good as join and there is no thing to worry about?

    Read the article

1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >