Search Results

Search found 35 results on 2 pages for 'subselect'.

Page 1/2 | 1 2  | Next Page >

  • NULL handling with subselect in Hibernate Criteria API

    - by Jens Schauder
    I'm constructing a Hibernate Criterion, using a subselect as follows DetachedCriteria subselect = DetachedCriteria.forClass(NhmCode.class, "sub"); // the subselect selecting the maximum 'validFrom' subselect.add(Restrictions.le("validFrom", new Date())); // it should be in the past (null needs handling here) subselect.add(Property.forName("sub.lifeCycle").eqProperty("this.id")); // join to owning entity subselect.setProjection(Projections.max("validFrom")); // we are only interested in the maximum validFrom Conjunction resultCriterion = Restrictions.conjunction(); resultCriterion.add(Restrictions.ilike(property, value)); // I have other Restrictions as well resultCriterion.add(Property.forName("validFrom").eq(subselect)); // this fails when validFrom and the subselect return NULL return resultCriterion; It works ok so far, but the restriction on the last line before the return statement is false when validFrom and subselect result in NULL. What I need is a version which handles this case as true. Possibly by applying a NVL or coalesce or similar. How do I do this?

    Read the article

  • How to Prove that using subselect queries in SQL is killing performance of server

    - by adopilot
    One of my jobs it to maintain our database, usually we have troubles with lack of performance while getting reports and working whit that base. When I start looking at queries which our ERP sending to database I see a lot of totally needlessly subselect queries inside main queries. As I am not member of developers which is creator of program we using, they do not like much when I criticize they code and job. Let say they do not taking my review as serious statements. So I asking you few questions about subselect in SQL Does subselect is taking a lot of more time then left outer joins? Does exists any blog, article or anything where I subselect is recommended not to use ? How I can prove that if we avoid subselesct in query that query is going to be faster ? Our database server is MSSQL2005

    Read the article

  • Using subselect to accomplish LEFT JOIN

    - by Andre
    Is is possible to accomplish the equivalent of a LEFT JOIN with subselect where multiple columns are required. Here's what I mean. SELECT m.*, (SELECT * FROM model WHERE id = m.id LIMIT 1) AS models FROM make m As it stands now doing this gives me a 'Operand should contain 1 column(s)' error. Yes I know this is possible with LEFT JOIN, but I was told it was possible with subselect to I'm curious as to how it's done.

    Read the article

  • slow mysql count because of subselect

    - by frgt10
    how to make this select statement more faster? the first left join with the subselect is making it slower... mysql> SELECT COUNT(DISTINCT w1.id) AS AMOUNT FROM tblWerbemittel w1 JOIN tblVorgang v1 ON w1.object_group = v1.werbemittel_id INNER JOIN ( SELECT wmax.object_group, MAX( wmax.object_revision ) wmaxobjrev FROM tblWerbemittel wmax GROUP BY wmax.object_group ) AS wmaxselect ON w1.object_group = wmaxselect.object_group AND w1.object_revision = wmaxselect.wmaxobjrev LEFT JOIN ( SELECT vmax.object_group, MAX( vmax.object_revision ) vmaxobjrev FROM tblVorgang vmax GROUP BY vmax.object_group ) AS vmaxselect ON v1.object_group = vmaxselect.object_group AND v1.object_revision = vmaxselect.vmaxobjrev LEFT JOIN tblWerbemittel_has_tblAngebot wha ON wha.werbemittel_id = w1.object_group LEFT JOIN tblAngebot ta ON ta.id = wha.angebot_id LEFT JOIN tblLieferanten tl ON tl.id = ta.lieferant_id AND wha.zuschlag = (SELECT MAX(zuschlag) FROM tblWerbemittel_has_tblAngebot WHERE werbemittel_id = w1.object_group) WHERE w1.flags =0 AND v1.flags=0; +--------+ | AMOUNT | +--------+ | 1982 | +--------+ 1 row in set (1.30 sec) Some indexes has been already set and as EXPLAIN shows they were used. +----+--------------------+-------------------------------+--------+----------------------------------------+----------------------+---------+-----------------------------------------------+------+----------------------------------------------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +----+--------------------+-------------------------------+--------+----------------------------------------+----------------------+---------+-----------------------------------------------+------+----------------------------------------------+ | 1 | PRIMARY | <derived2> | ALL | NULL | NULL | NULL | NULL | 2072 | | | 1 | PRIMARY | v1 | ref | werbemittel_group,werbemittel_id_index | werbemittel_group | 4 | wmaxselect.object_group | 2 | Using where | | 1 | PRIMARY | <derived3> | ALL | NULL | NULL | NULL | NULL | 3376 | | | 1 | PRIMARY | w1 | eq_ref | object_revision,or_og_index | object_revision | 8 | wmaxselect.wmaxobjrev,wmaxselect.object_group | 1 | Using where | | 1 | PRIMARY | wha | ref | PRIMARY,werbemittel_id_index | werbemittel_id_index | 4 | dpd.w1.object_group | 1 | | | 1 | PRIMARY | ta | eq_ref | PRIMARY | PRIMARY | 4 | dpd.wha.angebot_id | 1 | | | 1 | PRIMARY | tl | eq_ref | PRIMARY | PRIMARY | 4 | dpd.ta.lieferant_id | 1 | Using index | | 4 | DEPENDENT SUBQUERY | tblWerbemittel_has_tblAngebot | ref | PRIMARY,werbemittel_id_index | werbemittel_id_index | 4 | dpd.w1.object_group | 1 | | | 3 | DERIVED | vmax | index | NULL | object_revision_uq | 8 | NULL | 4668 | Using index; Using temporary; Using filesort | | 2 | DERIVED | wmax | range | NULL | or_og_index | 4 | NULL | 2168 | Using index for group-by | +----+--------------------+-------------------------------+--------+----------------------------------------+----------------------+---------+-----------------------------------------------+------+----------------------------------------------+ 10 rows in set (0.01 sec) The main problem while the statement above takes about 2 seconds seems to be the subselect where no index can be used. How to write the statement even more faster? Thanks for help. MT

    Read the article

  • A better way to build this MySQL statement with subselects

    - by Corey Maass
    I have five tables in my database. Members, items, comments, votes and countries. I want to get 10 items. I want to get the count of comments and votes for each item. I also want the member that submitted each item, and the country they are from. After posting here and elsewhere, I started using subselects to get the counts, but this query is taking 10 seconds or more! SELECT `items_2`.*, (SELECT COUNT(*) FROM `comments` WHERE (comments.Script = items_2.Id) AND (comments.Active = 1)) AS `Comments`, (SELECT COUNT(votes.Member) FROM `votes` WHERE (votes.Script = items_2.Id) AND (votes.Active = 1)) AS `votes`, `countrys`.`Name` AS `Country` FROM `items` AS `items_2` INNER JOIN `members` ON items_2.Member=members.Id AND members.Active = 1 INNER JOIN `members` AS `members_2` ON items_2.Member=members.Id LEFT JOIN `countrys` ON countrys.Id = members.Country GROUP BY `items_2`.`Id` ORDER BY `Created` DESC LIMIT 10 My question is whether this is the right way to do this, if there's better way to write this statement OR if there's a whole different approach that will be better. Should I run the subselects separately and aggregate the information?

    Read the article

  • mysql subselect alternative

    - by Arnold
    Hi, Lets say I am analyzing how high school sports records affect school attendance. So I have a table in which each row corresponds to a high school basketball game. Each game has an away team id and a home team id (FK to another "team table") and a home score and an away score and a date. I am writing a query that matches attendance with this seasons basketball games. My sample output will be (#_students_missed_class, day_of_game, home_team, away_team, home_team_wins_this_season, away_team_wins_this_season) I now want to add how each team did the previous season to my analysis. Well, I have their previous season stored in the game table but i should be able to accomplish that with a subselect. So in my main select statement I add the subselect: SELECT COUNT(*) FROM game_table WHERE game_table.date BETWEEN 'start of previous season' AND 'end of previous season' AND ( (game_table.home_team = team_table.id AND game_table.home_score > game_table.away_score) OR (game_table.away_team = team_table.id AND game_table.away_score > game_table.home_score)) In this case team-table.id refers to the id of the home_team so I now have all their wins calculated from the previous year. This method of calculation is neither time nor resource intensive. The Explain SQL shows that I have ALL in the Type field and I am not using a Key and the query times out. I'm not sure how I can accomplish a more efficient query with a subselect. It seems proposterously inefficient to have to write 4 of these queries (for home wins, home losses, away wins, away losses). I am sure this could be more lucid. I'll absolutely add color tomorrow if anyone has questions

    Read the article

  • Converting SQL with subselect in select to HQL

    - by UltraVi01
    I have the following SQL that I am having problems converting to HQL. A NPE is getting thrown -- which I think has something to do with the SUM function. Also, I'd like to sort on the subselect alias -- is this possible? SQL (subselect): SELECT q.title, q.author_id, (SELECT IFNULL(SUM(IF(vote_up=true,1,-1)), 0) FROM vote WHERE question_id = q.id) AS votecount FROM question q ORDER BY votecount DESC HQL (not working) SELECT q, (SELECT COALESCE(SUM(IF(v.voteUp=true,1,-1)), 0) FROM Vote v WHERE v.question = q) AS votecount FROM Question AS q LEFT JOIN q.author u LEFT JOIN u.blockedUsers ub WHERE q.dateCreated BETWEEN :week AND :now AND u.id NOT IN ( SELECT ub.blocked FROM UserBlock AS ub WHERE ub.blocker =:loggedInUser ) AND (u.blockedUsers IS EMPTY OR ub.blocked !=:loggedInUser) ORDER BY votecount DESC

    Read the article

  • Nhibernate many to many criteria query with subselect

    - by Max
    I have a simple example of a blog: a Post table, a Tag table and a Post_Tag_MM lookup table linking the two tables. I use this hql query in order to fetch all posts, that DONT have some tags: var result = session .CreateQuery(@" select p from Post p join p.Tags t where (select count(ti) from p.Tags ti where ti.Uid in (:uidList)) = 0 ") .SetParameterList("uidList", uidList) .SetResultTransformer(new DistinctRootEntityResultTransformer()) .List<Post>(); How can this many-to-many query and the subselect translated into a criteria query? I dont quite understand the DetachedCriteria API yet and could not get it to return the right resultset. Thank you very much in advance. Regards, Max

    Read the article

  • Nhibernate HQL Subselect queries

    - by MegaByte
    Hi I have the following SQL query: select c.id from (select id from customers) c This query has no practical value - I simplified it greatly for the purpose of this post. My question: is it possible have a subquery in the from clause using HQL. If not, can I perhaps query the customers first, kinda like a temp table in sql, and then use the result as the source of the next query? thanks

    Read the article

  • Multiple column subselect in mysql 5 (5.1.42)

    - by rubber boots
    This one seems to be a simple problem, but I can't make it work in a single select or nested select. Retrieve the authors and (if any) advisers of a paper (article) into one row. I order to explain the problem, here are the two data tables (pseudo) papers (id, title, c_year) persons (id, firstname, lastname) plus a link table w/one extra attribute (pseudo): paper_person_roles( paper_id person_id act_role ENUM ('AUTHOR', 'ADVISER') ) This is basically a list of written papers (table: papers) and a list of staff and/or students (table: persons) An article my have (1,N) authors. An article may have (0,N) advisers. A person can be in 'AUTHOR' or 'ADVISER' role (but not at the same time). The application eventually puts out table rows containing the following entries: TH: || Paper_ID | Author(s) | Title | Adviser(s) | TD: || 21334 |John Doe, Jeff Tucker|Why the moon looks yellow|Brown, Rayleigh| ... My first approach was like: select/extract a full list of articles into the application, eg.SELECT q.id, q.title FROM papers AS q ORDER BY q.c_year and save the results of the query into an array (in the application). After this step, loop over the array of the returned information and retrieve authors and advisers (if any), via prepared statement (? is the paper's id) from the link table like:APPLICATION_LOOP(paper_ids in array) SELECT p.lastname, p.firstname, r.act_role FROM persons AS p, paper_person_roles AS r WHERE p.id=r.person_id AND r.paper_id = ? # The application does further processing from here (pseudo): foreach record from resulting records if record.act_role eq 'AUTHOR' then join to author_column if record.act_role eq 'ADVISER' then join to avdiser_column end print id, author_column, title, adviser_column APPLICATION_LOOP This works so far and gives the desired output. Would it make sense to put the computation back into the DB? I'm not very proficient in nontrivial SQL and can't find a solution with a single (combined or nested) select call. I tried sth. like SELECT q.title (CONCAT_WS(' ', (SELECT p.firstname, p.lastname AS aunames FROM persons AS p, paper_person_roles AS r WHERE q.id=r.paper_id AND r.act_role='AUTHOR') ) ) AS aulist FROM papers AS q, persons AS p, paper_person_roles AS r in several variations, but no luck ... Maybe there is some chance? Thanks in advance r.b.

    Read the article

  • Subselecting with MDX

    - by Vince
    Greetings stack overflow community. I've recently started building an OLAP cube in SSAS2008 and have gotten stuck. I would be grateful if someone could at least point me towards the right direction. Situation: Two fact tables, same cube. FactCalls holds information about calls made by subscribers, FactTopups holds topup data. Both tables have numerous common dimensions one of them being the Subscriber dimension. FactCalls             FactTopups SubscriberKey      SubscriberKey CallDuration         DateKey CallCost               Topup Value ... What I am trying to achieve is to be able to build FactCalls reports based on distinct subscribers that have topped up their accounts within the last 7 days. What I am basically looking for an MDX equivalent to SQL's: select * from FactCalls where SubscriberKey in ( select distinct SubscriberKey from FactTopups where ... ); I've tried creating a degenerate dimension for both tables containing SubscriberKey and doing: Exist( [Calls Degenerate].[Subscriber Key].Children, [Topups Degenerate].[Subscriber Key].Children ) Without success. Kind regards, Vince

    Read the article

  • Return pre-UPDATE column values in PostgreSQL without using triggers, functions or other "magic"

    - by Python Larry
    I have a related question, but this is another part of MY puzzle. I would like to get the OLD VALUE of a Column from a Row that was UPDATEd... WITHOUT using Triggers (nor Stored Procedures, nor any other extra, non-SQL/-query entities). The query I have is like this: UPDATE my_table SET processing_by = our_id_info -- unique to this instance WHERE trans_nbr IN ( SELECT trans_nbr FROM my_table GROUP BY trans_nbr HAVING COUNT(trans_nbr) > 1 LIMIT our_limit_to_have_single_process_grab ) RETURNING row_id If I could do "FOR UPDATE ON my_table" at the end of the subquery, that'd be devine (and fix my other question/problem). But, that won't work: can't have this AND a "GROUP BY" (which is necessary for figuring out the COUNT of trans_nbr's). Then I could just take those trans_nbr's and do a query first to get the (soon-to-be-) former processing_by values. I've tried doing like: UPDATE my_table SET processing_by = our_id_info -- unique to this instance FROM my_table old_my_table JOIN ( SELECT trans_nbr FROM my_table GROUP BY trans_nbr HAVING COUNT(trans_nbr) > 1 LIMIT our_limit_to_have_single_process_grab ) sub_my_table ON old_my_table.trans_nbr = sub_my_table.trans_nbr WHERE my_table.trans_nbr = sub_my_table.trans_nbr AND my_table.processing_by = old_my_table.processing_by RETURNING my_table.row_id, my_table.processing_by, old_my_table.processing_by But that can't work; "old_my_table" is not viewable outside of the join; the RETURNING clause is blind to it. I've long since lost count of all the attempts I've made; I have been researching this for literally hours. If I could just find a bullet-proof way to lock the rows in my subquery - and ONLY those rows, and WHEN the subquery happens - all the concurrency issues I'm trying to avoid disappear... UPDATE: [WIPES EGG OFF FACE] Okay, so I had a typo in the non-generic code of the above that I wrote "doesn't work"; it does... thanks to Erwin Brandstetter, below, who stated it would, I re-did it (after a night's sleep, refreshed eyes, and a banana for bfast). Since it took me so long/hard to find this sort of solution, perhaps my embarrassment is worth it? At least this is on SO for posterity now... : What I now have (that works) is like this: UPDATE my_table SET processing_by = our_id_info -- unique to this instance FROM my_table AS old_my_table WHERE trans_nbr IN ( SELECT trans_nbr FROM my_table GROUP BY trans_nbr HAVING COUNT(*) > 1 LIMIT our_limit_to_have_single_process_grab ) AND my_table.row_id = old_my_table.row_id RETURNING my_table.row_id, my_table.processing_by, old_my_table.processing_by AS old_processing_by The COUNT(*) is per a suggestion from Flimzy in a comment on my other (linked above) question. (I was more specific than necessary. [In this instance.])

    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

  • Need help tuning a SQL statement

    - by jeffself
    I've got a table that has two fields (custno and custno2) that need to be searched from a query. I didn't design this table, so don't scream at me. :-) I need to find all records where either the custno or custno2 matches the value returned from a query on the same table based on a titleno. In other words, the user types in 1234 for the titleno. My query searches the table to find the custno associated with the titleno. It also looks for the custno2 for that titleno. Then it needs to do a search on the same table for all other records that have either the custno or custno2 returned in the previous search in the custno or custno2 fields for those other records. Here is what I've come up with: SELECT BILLYR, BILLNO, TITLENO, VINID, TAXPAID, DUEDATE, DATEPIF, PROPDESC FROM TRCDBA.BILLSPAID WHERE CUSTNO IN (select custno from trcdba.billspaid where titleno = '1234' union select custno2 from trcdba.billspaid where titleno = '1234' and custno2 != '') OR CUSTNO2 IN (select custno from trcdba.billspaid where titleno = '1234' union select custno2 from trcdba.billspaid where titleno = '1234' and custno2 != '') The query takes about 5-10 seconds to return data. Can it be rewritten to work faster?

    Read the article

  • Need to speed up the results of this SQL statement. Any advice?

    - by jeffself
    I've got the following SQL Statement that needs some major speed up. The problem is I need to search on two fields, where each of them is calling several sub-selects. Is there a way to join the two fields together so I call the sub-selects only once? SELECT billyr, billno, propacct, vinid, taxpaid, duedate, datepif, propdesc FROM trcdba.billspaid WHERE date(datepif) > '01/06/2009' AND date(datepif) <= '01/06/2010' AND custno in (select custno from cwdba.txpytaxid where taxpayerno in (select taxpayerno from cwdba.txpyaccts where accountno in (select accountno from rtadba.reasacct where controlno = 1234567))) OR custno2 in (select custno from cwdba.txpytaxid where taxpayerno in (select taxpayerno from cwdba.txpyaccts where accountno in (select accountno from rtadba.reasacct where controlno = 1234567)))

    Read the article

  • Oracle SQL: Multiple Subqueries Unioned Without Running Original Query Multiple Times.

    - by Bob
    So I've got a very large database, and need to work on a subset ~1% of the data to dump into an excel spreadsheet to make a graph. Ideally, I could select out the subset of data and then run multiple select queries on that, which are then UNION'ed together. Is this even possible? I can't seem to find anyone else trying to do this and would improve the performance of my current query quite a bit. Right now I have something like this: SELECT ( SELECT ( SELECT( long list of requirements ) UNION SELECT( slightly different long list of requirements ) ) ) and it would be nice if i could group the commonalities of the two long requirements and have simple differences between the two select statements being unioned.

    Read the article

  • How to correctly do SQL UPDATE with weighted subselect?

    - by luminarious
    I am probably trying to accomplish too much in a single query, but have I an sqlite database with badly formatted recipes. This returns a sorted list of recipes with relevance added: SELECT *, sum(relevance) FROM ( SELECT *,1 AS relevance FROM recipes WHERE ingredients LIKE '%milk%' UNION ALL SELECT *,1 AS relevance FROM recipes WHERE ingredients LIKE '%flour%' UNION ALL SELECT *,1 AS relevance FROM recipes WHERE ingredients LIKE '%sugar%' ) results GROUP BY recipeID ORDER BY sum(relevance) DESC; But I'm now stuck with a special case where I need to write the relevance value to a field on the same row as the recipe. I figured something along these lines: UPDATE recipes SET relevance=(SELECT sum(relevance) ...) But I have not been able to get this working yet. I will keep trying, but meanwhile please let me know how you would approach this?

    Read the article

  • Hibernate: Perform criteria query with Sub-Select AND Left-Outer join?

    - by Markos Fragkakis
    Can I perform a Criteria query with Sub-Select AND Left-Outer join? For example, I have A 1-many B 1-many C. With Criteria.createAlias ("b", "b", Criteria.LEFT_JOIN) I can perform Left Outer join. With Criteria.setFetchMode ("b", org.hibernate.FetchMode.DEFAULT) I can perform Join with the default fetching strategy. I assume that having set @org.hibernate.annotations.FetchMode.SUBSELECT in both A.B and B.C is enough (is it?). Question 1: Why does org.hibernate.FetchMode not have SUBSELECT option, whereas the org.hibernate.annotations.FetchMode does? Question 2: Can I perform a Criteria query with Sub-Select AND Left-Outer join?

    Read the article

  • Mysql Select 1:n

    - by clinisbut
    Hello, I have two tables that relates 1:n content --------- - id - title - text content_meta ------------- - id - content_id - meta_key - meta_value A content can have multiple content_meta registers associated to it. Typically content_meta will contain the category, tags, descriptions and all that stuff, so I really don't know the number of registers a content will have. What I want to accomplish is to take the content register and also all the related registers in content_meta in a single query. I've tried the subselect approachment but seems that I can only get one register/column (¿?) SELECT content.*, ( SELECT * FROM content_meta WHERE content_id = content.id ) FROM content This query complains that "Operand should contain 1 column(s)", so changing the '*' by for example meta_key clears the error, but returns a NULL for this subselect... SELECT content.*, ( SELECT meta_key FROM content_meta WHERE content_id = content.id ) FROM content Can anybody show me where to go from here please?

    Read the article

  • nhibernate will not cascade delete childs

    - by marn
    The scenario is as follows, I have 3 objects (i simplified the names) named Parent, parent's child & child's child parent's child is a set in parent, and child's child is a set in child. mapping is as follows (relevant parts) parent <set name="parentset" table="pc-table" lazy="false" fetch="subselect" cascade="all-delete-orphan" inverse="true"> <key column=FK_ID_PC" on-delete="cascade"/> <one-to-many class="parentchild,parentchild-ns"/> </set> parent's child <set name="childset" table="cc-table" lazy="false" fetch="subselect" cascade="all-delete-orphan" inverse="true"> <key column="FK_ID_CC" on-delete="cascade"/> <one-to-many class="childschild,childschild-ns"/> </set> What i want to achieve is that when i delete the parent, there would be a cascade delete all the way trough to child's child. But what currently happens is this. (this is purely for mapping test purposes) getting a parent entity (works fine) IQuery query = session.CreateQuery("from Parent where ID =" + ID); IParent doc = query.UniqueResult<Parent>(); now the delete part session.Delete(doc); transaction.Commit(); After having solved the 'cannot insert null value' error with cascading and inverse i hopes this would now delete everything with this code, but only the parent is being deleted. Did i miss something in my mapping which is likely to be missed? Any hint in the right direction is more than welcome!

    Read the article

  • Help with HQL Query (find duplicates)

    - by BRhodes
    I am trying to convert this native sql into an HQL query. Basically it returns all the contacts that are duplicates (by company, firstname, and lastname). The query below works great, but performing a joined subselect seems impossible in HQL is it not?! Select c.* from contact c join ( Select c2.* from contact c2 group by c2.company, c2.firstname, c2.lastname, c2.teamId having count(c2.contactId)1 and teamId=1 ) dupes on c.company=dupes.company and c.teamId=1 and c.firstname=dupes.firstname and c.lastname=dupes.lastname order by c.company, c.firstname, c.lastname

    Read the article

  • Mysql Sub Select Query Optimization

    - by Matt
    I'm running a query daily to compile stats - but it seems really inefficient. This is the Query: SELECT a.id, tstamp, label_id, (SELECT author_id FROM b WHERE b.tid = a.id ORDER BY b.tstamp DESC LIMIT 1) AS author_id FROM a, b WHERE (status = '2' OR status = '3') AND category != 6 AND a.id = b.tid AND (b.type = 'C' OR b.type = 'R') AND a.tstamp1 BETWEEN {$timestamp_start} AND {$timestamp_end} ORDER BY b.tstamp DESC LIMIT 500 This query seems to run really slow. Apologies for the crap naming - I've been asked to not reveal the actual table names. The reason there is a sub select is because the outer select gets one row from the table a and it gets a row from table b. But also need to know the latest author_id from table b as well, so I run a subselect to return that one. I don't want to run another select inside a php loop - as that is also inefficient. It works correctly - I just need to find a much faster way of getting this data set.

    Read the article

  • Mixing inheritance mapping strategies in NHibernate

    - by MylesRip
    I have a rather large inheritance hierarchy in which some of the subclasses add very little and others add quite a bit. I don't want to map the entire hierarchy using either "table per class hierarchy" or "table per subclass" due to the size and complexity of the hierarchy. Ideally I'd like to mix mapping strategies such that portions of the hierarchy where the subclasses add very little are combined into a common table a la "table per class hierarchy" and subclasses that add a lot are broken out into a separate table. Using this approach, I would expect to have 2 or 3 tables with very little wasted space instead of either 1 table with lots of fields that don't apply to most of the objects, or 20+ tables, several of which would have only a couple of columns. In the NHibernate Reference Documentation version 2.1.0, I found section 8.1.4 "Mixing table per class hierarchy with table per subclass". This approach switches strategies partway down the hierarchy by using: ... <subclass ...> <join ...> <property ...> ... </join> </subclass> ... This is great in theory. In practice, though, I found that the schema was too restrictive in what was allowed inside the "join" element for me to be able to accomplish what I needed. Here is the related part of the schema definition: <xs:element name="join"> <xs:complexType> <xs:sequence> <xs:element ref="subselect" minOccurs="0" /> <xs:element ref="comment" minOccurs="0" /> <xs:element ref="key" /> <xs:choice minOccurs="0" maxOccurs="unbounded"> <xs:element ref="property" /> <xs:element ref="many-to-one" /> <xs:element ref="component" /> <xs:element ref="dynamic-component" /> <xs:element ref="any" /> <xs:element ref="map" /> <xs:element ref="set" /> <xs:element ref="list" /> <xs:element ref="bag" /> <xs:element ref="idbag" /> <xs:element ref="array" /> <xs:element ref="primitive-array" /> </xs:choice> <xs:element ref="sql-insert" minOccurs="0" /> <xs:element ref="sql-update" minOccurs="0" /> <xs:element ref="sql-delete" minOccurs="0" /> </xs:sequence> <xs:attribute name="table" use="required" type="xs:string" /> <xs:attribute name="schema" type="xs:string" /> <xs:attribute name="catalog" type="xs:string" /> <xs:attribute name="subselect" type="xs:string" /> <xs:attribute name="fetch" default="join"> <xs:simpleType> <xs:restriction base="xs:string"> <xs:enumeration value="join" /> <xs:enumeration value="select" /> </xs:restriction> </xs:simpleType> </xs:attribute> <xs:attribute name="inverse" default="false" type="xs:boolean"> </xs:attribute> <xs:attribute name="optional" default="false" type="xs:boolean"> </xs:attribute> </xs:complexType> </xs:element> As you can see, this allows the use of "property" child elements or "component" child elements, but not both. It also doesn't allow for "subclass" child elements to continue the hierarchy below the point at which the strategy was changed. Is there a way to accomplish this?

    Read the article

  • SQL for selecting only the last item from a versioned table

    - by Jeremy
    I have a table with the following structure: CREATE TABLE items ( id serial not null, title character varying(255), version_id integer DEFAULT 1, parent_id integer, CONSTRAINT items_pkey PRIMARY KEY (id) ) So the table contains rows that looks as so: id: 1, title: "Version 1", version_id: 1, parent_id: 1 id: 2, title: "Version 2", version_id: 2, parent_id: 1 id: 3, title: "Completely different record", version_id: 1, parent_id: 3 This is the SQL code I've got for selecting out all of the records with the most recent version ids: select * from items inner join ( select parent_id, max(version_id) as version_id from items group by parent_id) as vi on items.version_id = vi.version_id and items.parent_id = vi.parent_id Is there a way to write that SQL statement so that it doesn't use a subselect?

    Read the article

  • Fill object data from several tables using hibernate mapping

    - by Udo Fholl
    Hi all, I'd like to know if it is possible to fill up a class data from database using the hibernate hbm (mapping). For instance: public class someClass { List<OtherClass> otherClasses; List<YetAnotherClass> yetAnotherClasses; //Constructors ? class OtherClass { String name; //setters, getters } class YetAnotherClass { String name; //setters, getters } //setters, getters } Using an hbm can I fill in the data from tables OTHER_CLASS_TABLE and YET_ANOTHER_CLASS_TABLE? I have no such SOME_CLASS_TABLE since this info is for viewing only. I've been playing with the <join table=""><subselect> and different constructors... But it is not working Thanks! Sorry for my english!

    Read the article

1 2  | Next Page >