Search Results

Search found 6841 results on 274 pages for 'outer join'.

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

  • Excessive use of Inner Join for more than 3 tables

    - by Archangel08
    Good Day, I have 4 tables on my DB (not the actual name but almost similar) which are the ff: employee,education,employment_history,referrence employee_id is the name of the foreign key from employee table. Here's the example (not actual) data: **Employee** ID Name Birthday Gender Email 1 John Smith 08-15-2014 Male [email protected] 2 Jane Doe 00-00-0000 Female [email protected] 3 John Doe 00-00-0000 Male [email protected] **Education** Employee_ID Primary Secondary Vocation 1 Westside School Westshore H.S SouthernBay College 2 Eastside School Eastshore H.S NorthernBay College 3 Northern School SouthernShore H.S WesternBay College **Employment_History** Employee_ID WorkOne StartDate Enddate 1 StarBean Cafe 12-31-2012 01-01-2013 2 Coffebucks Cafe 11-01-2012 11-02-2012 3 Latte Cafe 01-02-2013 04-05-2013 Referrence Employee_ID ReferrenceOne Address Contact 1 Abraham Lincoln Lincoln Memorial 0000000000 2 Frankie N. Stein Thunder St. 0000000000 3 Peter D. Pan Neverland Ave. 0000000000 NOTE: I've only included few columns though the rest are part of the query. And below are the codes I've been working on for 3 consecutive days: $sql=mysql_query("SELECT emp.id,emp.name,emp.birthday,emp.pob,emp.gender,emp.civil,emp.email,emp.contact,emp.address,emp.paddress,emp.citizenship,educ.employee_id,educ.elementary,educ.egrad,educ.highschool,educ.hgrad,educ.vocational,educ.vgrad,ems.employee_id,ems.workOne,ems.estartDate,ems.eendDate,ems.workTwo,ems.wstartDate,ems.wendDate,ems.workThree,ems.hstartDate,ems.hendDate FROM employee AS emp INNER JOIN education AS educ ON educ.employee_id='emp.id' INNER JOIN employment_history AS ems ON ems.employee_id='emp.id' INNER JOIN referrence AS ref ON ref.employee_id='emp.id' WHERE emp.id='$id'"); Is it okay to use INNER JOIN this way? Or should I modify my query to get the results that I wanted? I've also tried to use LEFT JOIN but still it doesn't return anything .I didn't know where did I go wrong. You see, as I have thought, I've been using the INNER JOIN in correct manner, (since it was placed before the WHILE CLAUSE). So I couldn't think of what could've possible went wrong. Do you guys have a suggestion? Thanks in advance.

    Read the article

  • Oracle SQL outer join query puzzle

    - by user1651446
    So I am dumb and I have this: select whatever from bank_accs b1, bank_accs b2, table3 t3 where t3.bank_acc_id = t1.bank_acc_id and b2.bank_acc_number = b1.bank_acc_number and b2.currency_code(+) = t3.buy_currency and trunc(sysdate) between nvl(b2.start_date, trunc(sysdate)) and nvl(b2.end_date, trunc(sysdate)); My problem is with the date (actuality) check on b2. Now, I need to return a row for each t3xb1 (t3 = ~10 tables joined, of course), even if there are ONLY INVALID records (date-wise) in b2. How do I outer-join this bit properly? Can't use ANSI joins, must do in a single flat query. Thanks.

    Read the article

  • Linq to Entity Left Outer Join

    - by radman
    Hi All, I have an Entity model with Invoices, AffiliateCommissions and AffiliateCommissionPayments. Invoice to AffiliateCommission is a one to many, AffiliateCommission to AffiliateCommissionPayment is also a one to many I am trying to make a query that will return All Invoices that HAVE a commission but not necessarily have a related commissionPayment. I want to show the invoices with commissions whether they have a commission payment or not. Query looks something like: using (var context = new MyEntitities()) { var invoices = from i in context.Invoices from ac in i.AffiliateCommissions join acp in context.AffiliateCommissionPayments on ac.affiliateCommissionID equals acp.AffiliateCommission.affiliateCommissionID where ac.Affiliate.affiliateID == affiliateID select new { companyName = i.User.companyName, userName = i.User.fullName, email = i.User.emailAddress, invoiceEndDate = i.invoicedUntilDate, invoiceNumber = i.invoiceNumber, invoiceAmount = i.netAmount, commissionAmount = ac.amount, datePaid = acp.paymentDate, checkNumber = acp.checkNumber }; return invoices.ToList(); } This query above only returns items with an AffiliateCommissionPayment.

    Read the article

  • mysql filtering result using left outer join

    - by user288178
    my query: SELECT content.*, activity_log.content_id FROM content LEFT JOIN activity_log ON content.id = activity_log.content_id AND sess_id = '$sess_id' WHERE activity_log.content_id IS NULL AND visibility = $visibility AND content.reported < ".REPORTED_LIMIT." AND content.file_ready = 1 LIMIT 1 The purpose of that query is to get 1 row from the content table that has not been viewed by the user (identified by session_id), but it still returns contents that have been viewed. What is wrong? ( I have checked the table making sure that the content_ids are there) Note: I think this is more efficient than using subqueries, thoughts?

    Read the article

  • SQL SERVER – Subquery or Join – Various Options – SQL Server Engine Knows the Best – Part 2

    - by pinaldave
    This blog post is part 2 of the earlier written article SQL SERVER – Subquery or Join – Various Options – SQL Server Engine knows the Best by Paulo R. Pereira. Paulo has left excellent comment to earlier article once again proving the point that SQL Server Engine is smart enough to figure out the best plan itself and uses the same for the query. Let us go over his comment as he has posted. “I think IN or EXISTS is the best choice, because there is a little difference between ‘Merge Join’ of query with JOIN (Inner Join) and the others options (Left Semi Join), and JOIN can give more results than IN or EXISTS if the relationship is 1:0..N and not 1:0..1. And if I try use NOT IN and NOT EXISTS the query plan is different from LEFT JOIN too (Left Anti Semi Join vs. Left Outer Join + Filter). So, I found a case where EXISTS has a different query plan than IN or ANY/SOME:” USE AdventureWorks GO -- use of SOME SELECT * FROM HumanResources.Employee E WHERE E.EmployeeID = SOME ( SELECT EA.EmployeeID FROM HumanResources.EmployeeAddress EA UNION ALL SELECT EA.EmployeeID FROM HumanResources.EmployeeDepartmentHistory EA ) -- use of IN SELECT * FROM HumanResources.Employee E WHERE E.EmployeeID IN ( SELECT EA.EmployeeID FROM HumanResources.EmployeeAddress EA UNION ALL SELECT EA.EmployeeID FROM HumanResources.EmployeeDepartmentHistory EA ) -- use of EXISTS SELECT * FROM HumanResources.Employee E WHERE EXISTS ( SELECT EA.EmployeeID FROM HumanResources.EmployeeAddress EA UNION ALL SELECT EA.EmployeeID FROM HumanResources.EmployeeDepartmentHistory EA ) When looked into execution plan of the queries listed above indeed we do get different plans for queries and SQL Server Engines creates the best (least cost) plan for each query. Click on image to see larger images. Thanks Paulo for your wonderful contribution. Reference : Pinal Dave (http://blog.SQLAuthority.com) Filed under: Pinal Dave, Readers Contribution, SQL, SQL Authority, SQL Joins, SQL Optimization, SQL Performance, SQL Query, SQL Scripts, SQL Server, SQL Tips and Tricks, T SQL, Technology

    Read the article

  • SQL Full Outer Join

    - by Torment March
    I have a table named 'Logs' with the following values : CheckDate CheckType CheckTime ------------------------------------------- 2011-11-25 IN 14:40:00 2011-11-25 OUT 14:45:00 2011-11-25 IN 14:50:00 2011-11-25 OUT 14:55:00 2011-11-25 IN 15:00:00 2011-11-25 OUT 15:05:00 2011-11-25 IN 15:15:00 2011-11-25 OUT 15:20:00 2011-11-25 IN 15:25:00 2011-11-25 OUT 15:30:00 2011-11-25 OUT 15:40:00 2011-11-25 IN 15:45:00 I want to use the previous table to produce a result of: CheckDate CheckIn CheckOut ----------------------------------------- 2011-11-25 14:40:00 14:45:00 2011-11-25 14:50:00 14:55:00 2011-11-25 15:00:00 15:05:00 2011-11-25 15:15:00 15:20:00 2011-11-25 15:25:00 15:30:00 2011-11-25 NULL 15:40:00 2011-11-25 15:45:00 NULL So far I have come up with this result set : CheckDate CheckIn CheckOut ----------------------------------------- 2011-11-25 14:40:00 14:45:00 2011-11-25 14:50:00 14:55:00 2011-11-25 15:00:00 15:05:00 2011-11-25 15:15:00 15:20:00 2011-11-25 15:25:00 15:30:00 2011-11-25 15:45:00 NULL The problem is I cannot generate the log without CheckIns : CheckDate CheckIn CheckOut ----------------------------------------- 2011-11-25 NULL 15:40:00 The sequence of CheckIn - CheckOut pairing and order is in increasing time value.

    Read the article

  • Join .doc files into one .doc (with keeping the original format of every document)

    - by Shiki
    I have about ~50 .doc files, that look perfect (they are extracted with Able2Extract). Now I want to join these 50 files into one huge .doc. I've tried using Word's in-built "Insert" feature, but that messed up the whole format. I want to keep everything I have. Like just document1 - document2 - document3. Nothing "intelligent" or "smart" needed during the conversion, just the capability of joining them. (Thus making them all searchable, that's the ultimate aim.) I don't mind if the method/solution applies a single blank page at every document end either.

    Read the article

  • problem with a join

    - by Luca Romagnoli
    I have this code: int se = (int) settings.GruppoSegreteria; var acc = db.USR_Accounts.Where( p => p.ID_Gruppo == se); var segreterie = from s in db.USR_Utenti join h in acc on s.ID equals h.USR_UtentiReference select s; And this error: The type of one of the expressions in the join clause is incorrect. Type inference failed in the call to 'Join' I don't understand it. Can you help me? thanks

    Read the article

  • mysql join Two tables to get records

    - by Saranya
    Hai guys, I have two tables Incharge and property. My property table has three fields 1stIncharge,2ndIncharge and 3rdIncharge. InchargeId is set as foreign key for all the above fields in the property table.. How to write a select statement that joins both the table.. I ve tried a bit but no result select P.Id,P.Name,P.1stIncharge,P.2ndIncharge,P.3rdIncharge,I.Id from Property as P join Incharge as I where (\\How to give condition here \\) Guys 3 fields P.1stIncharge, P.2ndIncharge, P.3rdIncharge has foreign key I.Id Edit: select P.Id,P.Name,P.1stIncharge,P.2ndIncharge,P.3rdIncharge,I1.Id from Property as P inner join Incharge as I1 on I1.Id=P.1stIncharge inner join Incharge as I2 on I2.Id=P.2ndIncharge inner join Incharge as I3 on I3.Id=P.3rdIncharge and this query working

    Read the article

  • Deleting rows with MySQL LEFT JOIN

    - by fabrik
    Hello! I have two tables, one for job deadlines, one for describe a job. Each job can take a status and some statuses means the jobs' deadlines must be deleted from the other table. I can easily SELECT the jobs/deadlines that meets my criteria with a LEFT JOIN: SELECT * FROM `deadline` LEFT JOIN `job` ON deadline.job_id = job.job_id WHERE `status` = 'szamlazva' OR `status` = 'szamlazhato' OR `status` = 'fizetve' OR `status` = 'szallitva' OR `status` = 'storno' (status belongs to job table not deadline) But when i'd like to delete these rows from deadline, MySQL throws an error. My query is: DELETE FROM `deadline` LEFT JOIN `job` ON deadline.job_id = job.job_id WHERE `status` = 'szamlazva' OR `status` = 'szamlazhato' OR `status` = 'fizetve' OR `status` = 'szallitva' OR `status` = 'storno' MySQL error says nothing: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'LEFT JOIN `job` ON deadline.job_id = job.job_id WHERE `status` = 'szaml' at line 1 How can i turn my SELECT into a working DELETE query? Thanks, fabrik

    Read the article

  • Left Join Returning Extra Rows T-SQL?

    - by davemackey
    I have the following query: select * from ACADEMIC a left join RESIDENCY r on a.PEOPLE_CODE_ID = r.PEOPLE_CODE_ID where a.ACADEMIC_TERM='Fall' and r.ACADEMIC_TERM='Fall' and a.ACADEMIC_SESSION='' and a.ACADEMIC_YEAR = (Select Year(GetDate())) and r.ACADEMIC_YEAR = (Select Year(GetDate())) and (CLASS_LEVEL LIKE 'FR%' OR a.CLASS_LEVEL LIKE 'SO' OR a.CLASS_LEVEL LIKE 'JR' OR a.CLASS_LEVEL LIKE 'SR%') and r.RESIDENT_COMMUTER='R' For each person in the database it returns two rows with identical information. Yet, when I do the same query without the left join: select * from ACADEMIC a where a.ACADEMIC_TERM='Fall' and a.ACADEMIC_SESSION='' and a.ACADEMIC_YEAR = (Select Year(GetDate())) and (CLASS_LEVEL LIKE 'FR%' OR a.CLASS_LEVEL LIKE 'SO' OR a.CLASS_LEVEL LIKE 'JR' OR a.CLASS_LEVEL LIKE 'SR%') ORDER BY PEOPLE_ID It returns only one row for each person. I'm doing a left join - why is it adding an extra row? Shouldn't it only do that if I add a right join?

    Read the article

  • SQL - Multiple join conditions using OR?

    - by Brandi
    I have a query that is using multiple joins. The goal is to say "Out of table A, give me all the customer numbers in which you can match table A's EmailAddress with either email_to or email_from of table B. Ignore nulls, internal emails, etc.". It seems like it would be better to use an or condition in the join than multiple joins since it is the same table. When I try to use AND/OR it does not give the behaviour I expect... AND finishes in a reasonable time, but yields no results (I know that there are matches, so it must be some flaw in my logic) and OR never finishes (I have to kill it). Here is example code to illustrate the question: --my original query SELECT DISTINCT a.CustomerNo FROM A a WITH (NOLOCK) LEFT JOIN B e WITH (NOLOCK) ON a.EmailAddress = e.email_from RIGHT JOIN B f WITH (NOLOCK) ON a.EmailAddress = f.email_to WHERE a.EmailAddress NOT LIKE '%@mydomain.___' AND a.EmailAddress IS NOT NULL AND (e.email_from IS NOT NULL OR f.email_to IS NOT NULL) Here is what I tried, (I am attempting logical equivalence): SELECT DISTINCT a.CustomerNo FROM A a WITH (NOLOCK) LEFT JOIN B e WITH (NOLOCK) ON a.EmailAddress = e.email_from OR a.EmailAddress = e.email_to WHERE a.EmailAddress NOT LIKE '%@mydomain.___' AND a.EmailAddress IS NOT NULL AND (e.email_from IS NOT NULL OR e.email_to IS NOT NULL) So my question is two-fold: Why does having AND in the above query work in a few seconds and OR goes for minutes and never completes? What am I missing to make a logically equivalent statement that has only one join?

    Read the article

  • Join two tables with same # of row but sorted for NULL

    - by VISQL
    I need to join two tables with the same number of rows. Each table has 1 column. There is NO CONNECTING COLUMN to reference for a join. I need to join them side by side because each table was sorted separately so that numeric values are at the top in descinding order. The Table Earners has income values from say 200K down to 0. I cannot just select using 2 cases, because then I will have my first row with Incomes above 100K, but the first 20 or so entries in the second row are NULL. I want the second row to also be sorted descending. I looked up using ORDER BY within CASE but there is no such thing. I have tried to read about row_number() but none of the examples seem to match or make sense. drop table #20plus select case when Income >= 20000 AND Income < 100000 then Income end as 'mula' into #20plus from Earners order by mula desc drop table #100plus select case when Income >= 100000 then Income end as 'dinero' into #100plus from Earners order by dinero desc Select A.dinero, B.mula FROM #100plus as A JOIN #20plus as B ON A.????? = B.????? Since both A and B are sorted descending, moving all NULL to the bottom, what can I reference to join the two tables? Previous output using one SELECT statement with 2 CASE statements dinero mula 2.12688e+007 NULL 1.80031e+007 NULL 1.92415e+006 NULL … … NULL 93530.7 NULL 91000 NULL 84500 Desired output using one SELECT statement after creating two temp TABLES dinero mula 2.12688e+007 93530.7 1.80031e+007 91000 1.92415e+006 84500 … 82500 NULL 82000 NULL … NULL NULL This is Microsoft SQL Server 2008. I'm super new to this, so please give an answer as clear and simplified as possible. Thank you.

    Read the article

  • LINQ-to-SQL - Join, Count

    - by ile
    I have following query: var result = ( from role in db.Roles join user in db.Users on role.RoleID equals user.RoleID where user.CreatedByUserID == userID orderby user.FirstName ascending select new UserViewModel { UserID = user.UserID, PhotoID = user.PhotoID.ToString(), FirstName = user.FirstName, LastName = user.LastName, FullName = user.FirstName + " " + user.LastName, Email = user.Email, PhoneNumber = user.Phone, AccessLevel = role.Name }); Now, I need to modify this query... Other table I have is table Deals. I would like to count how many deals user created last month and last year. I tried something like this: var result = ( from role in db.Roles join user in db.Users on role.RoleID equals user.RoleID //join dealsYear in db.Deals on date.Year equals dealsYear.DateCreated.Year join dealsYear in ( from deal in db.Deals group deal by deal.DateCreated into d select new { DateCreated = d.Key, dealsCount = d.Count() } ) on date.Year equals dealsYear.DateCreated.Year into dYear join dealsMonth in ( from deal in db.Deals group deal by deal.DateCreated into d select new { DateCreated = d.Key, dealsCount = d.Count() } ) on date.Month equals dealsMonth.DateCreated.Month into dMonth where user.CreatedByUserID == userID orderby user.FirstName ascending select new UserViewModel { UserID = user.UserID, PhotoID = user.PhotoID.ToString(), FirstName = user.FirstName, LastName = user.LastName, FullName = user.FirstName + " " + user.LastName, Email = user.Email, PhoneNumber = user.Phone, AccessLevel = role.Name, DealsThisYear = dYear, DealsThisMonth = dMonth }); but here is even syntax not correct. Any idea? Btw, is there any good book of LINQ to SQL with examples?

    Read the article

  • error with linq join

    - by Luca Romagnoli
    I have this linq query: var segreterie = from s in db.USR_Utenti join h in db.USR_Accounts on new {s.ID, settings.GruppoSegreteria} equals new {h.USR_UtentiReference,h.ID_Gruppo} select s; that has this problem: The type of one of the expressions in the join clause is incorrect. Type inference failed in the call to 'Join'. how can i do to solve it?

    Read the article

  • Why is my left join not returning nulls?

    - by Griz
    In sql server 2008, I have the following query: select c.title as categorytitle, s.title as subcategorytitle, i.title as itemtitle from categories c join subcategories s on c.categoryid = s.categoryid left join itemcategories ic on s.subcategoryid = ic.subcategoryid left join items i on ic.itemid = i.itemid where (ic.isactive = 1 or ic.isactive is null) and i.siteid = 132 order by c.title, s.title I am trying to get items in their subcategories, but I still want to return a record if there are no items in the category or subcategory. Subcategories that have no items are never returned. What am I doing wrong? Thank you EDIT Modified query with a second left join and where clause, but it's still not returning nulls. :/

    Read the article

  • join query with lowstock products with another table in magento

    - by muralikalpana
    I want to display some attributes in reports/products/lowstock grid. here how can i join another table with lowstock product id? here is the query /** @var $collection Mage_Reports_Model_Resource_Product_Lowstock_Collection */ $collection = Mage::getResourceModel('reports/product_lowstock_collection') ->addAttributeToSelect('*') ->setStoreId($storeId) ->filterByIsQtyProductTypes() ->joinInventoryItem('qty') ->joinInventoryItem('low_stock_date') ->useManageStockFilter($storeId) ->useNotifyStockQtyFilter($storeId) ->setOrder('qty', Varien_Data_Collection::SORT_ORDER_ASC); here i have to join with this productid with another table. i am not getting results if i use this query. $collection->getSelect()->join(array('t2' => 'lowstockorders'),'lowstock_inventory_item.product_id = t2.product_id','t2.product_id'); please anybody tell me how to join these tables thanks, murali

    Read the article

  • multiple join query in entity framework

    - by gvLearner
    I have following tables tasks id | name | proj_id 1 | task1 | 1 2 | task2 | 1 3 | task3 | 1 projects id | name 1 | sample proj1 2 | demo project budget_versions id | version_name| proj_id 1 | 50 | 1 budgets id | cost | budget_version_id | task_id 1 | 3000 | 1 | 2 2 | 5000 | 1 | 1 I need to join these tables to get a result as below task_id | task_name | project_id | budget_version | budget_id | cost 1 | task1 | 1 | 1 | 2 |5000 2 | task2 | 1 | 1 | 1 |3000 3 | task3 | 1 | NULL | NULL |NULL select tsk.id,tsk.name, tsk.project_id, bgtver.id, bgt.id, bgt.cost from TASK tsk left outer join BUDGET_VERSIONS bgtver on tsk.project_id= bgtver.project_id left outer join BUDGETS bgt on bgtver.id = bgt.budget_version_id and tsk.id = bgt.task_id where bgtver.id = 1

    Read the article

  • How do I write to an outer truecrypt volume when the inner volume protection prevents writng?

    - by con-f-use
    In a nutshell After some time using the outer volume of a hidden volume in Truecrypt I cannot write to the outer volume anymore. The protection of the inner volume always kicks in before. How do I fix this? Details I'm using truecrypt's two layered encryption of a USB stick. The outer container carries my semi-sensitive stuff while the inner hidden values has a bit more valuable information. I use both, the inner and outer volume regularly and that is part of the problem. Truecrypt can mount the outer volume for writing while protecting the inner. Usually the inner volume, when not protected this way (or mounted read-only) would be indistinguishable from free space. That is of course part of the plausible deniability scheme of truecrypt. At the beginning, everything worked as expected. I could copy and delete data to the outer volume as I pleased. Now it seams that I have written and deleted enough data to have filled the outer volume once. Despite the write protection Ubuntu tries now to write to the continuous "free space" that is the inner volume. It does that although enough other free space is on the outer volume. But on this free space there used to be data so its fragmented and the file system write prefers continuous space. The write on the continuous free space of the outer volume of course fails (with the error message in the picture above) as Truecrypt's inner-volume-protection kicks in. The Question I know this is expected behaviour, but is there a better way to write to the outer volume that does not attempt to write to the hidden free space at the end? The whole question could be more generally rephrased to: How do I control, where on a partition data is written in Ubuntu?

    Read the article

  • Join mp4 files in linux

    - by Jose Armando
    I want to join two mp4 files to create a single one. The video streams are encoded in h264 and the audio in aac. I can not re-encode the videos to another format due to computational reasons. Also, I cannot use any gui programs, all processing must be performed with linux command line utilities. FFmpeg cannot do this for mpeg4 files so instead I used MP4Box e.g. MP4Box -add video1.mp4 -cat video2.mp4 newvideo.mp4 unfortunately the audio gets all mixed up. I thought that the problem was that the audio was in aac so I transcoded it in mp3 and used again MP4Box. In this case the audio is fine for the first half of newvideo.mp4 (corresponding to video1.mp4) but then their is no audio and I cannot navigate in the video also. My next thought was that the audio and video streams had some small discrepancies in their lengths that I should fix. So for each input video I splitted the video and audio streams and then joined them with the -shortest option in ffmpeg. thus for the first video I ran avconv -y -i video1.mp4 -c copy -map 0:0 videostream1.mp4 avconv -y -i video1.mp4 -c copy -map 0:1 audiostream1.m4a avconv -y -i videostream1.mp4 -i audiostream1.m4a -c copy -shortest video1_aligned.mp4 similarly for the second video and then used MP4Box as previously. Unfortunately this didn't work either. The only success I had was when I joined the video streams separetely (i.e. videostream1.mp4 and videostream2.mp4) and the audio streams (i.e. audiostream1.m4a and audiostream2.m4a) and then joined the video and audio in a final file. However, the synchronization is lost for the second half of the video. Concretelly, there is a 1 sec delay of audio and video. Any suggestions are really welcome.

    Read the article

  • Linq, double left join and double count

    - by Fabian Vilers
    Hi! I'm looking to translate this SQL statement to a well working & performant LINQ command. I've managed to have the first count working using the grouping count and key members, but don't know how to get the second count. select main.title, count(details.id) as details, count(messages.id) as messages from main left outer join details on main.id = details.mainid left outer join messages on details.id = messages.detailid group by main.title Any advice is welcome! Fabian

    Read the article

  • Adding one subquery makes query a little slower, adding another makes it way slower

    - by Jason Swett
    This is fast: select ba.name, penamt.value penamt, #address_line4.value address_line4 from account a join customer c on a.customer_id = c.id join branch br on a.branch_id = br.id join bank ba on br.bank_id = ba.id join account_address aa on aa.account_id = a.id join address ad on aa.address_id = ad.id join state s on ad.state_id = s.id join import i on a.import_id = i.id join import_bundle ib on i.import_bundle_id = ib.id join (select * from unused where heading_label = 'PENAMT') penamt ON penamt.account_id = a.id #join (select * from unused where heading_label = 'Address Line 4') address_line4 ON address_line4.account_id = a.id where i.active=1 And this is fast: select ba.name, #penamt.value penamt, address_line4.value address_line4 from account a join customer c on a.customer_id = c.id join branch br on a.branch_id = br.id join bank ba on br.bank_id = ba.id join account_address aa on aa.account_id = a.id join address ad on aa.address_id = ad.id join state s on ad.state_id = s.id join import i on a.import_id = i.id join import_bundle ib on i.import_bundle_id = ib.id #join (select * from unused where heading_label = 'PENAMT') penamt ON penamt.account_id = a.id join (select * from unused where heading_label = 'Address Line 4') address_line4 ON address_line4.account_id = a.id where i.active=1 But this is slow: select ba.name, penamt.value penamt, address_line4.value address_line4 from account a join customer c on a.customer_id = c.id join branch br on a.branch_id = br.id join bank ba on br.bank_id = ba.id join account_address aa on aa.account_id = a.id join address ad on aa.address_id = ad.id join state s on ad.state_id = s.id join import i on a.import_id = i.id join import_bundle ib on i.import_bundle_id = ib.id join (select * from unused where heading_label = 'PENAMT') penamt ON penamt.account_id = a.id join (select * from unused where heading_label = 'Address Line 4') address_line4 ON address_line4.account_id = a.id where i.active=1 Why is it fast when I include just one of the two subqueries but slow when I include both? I would think it should be twice as slow when I include both, but it takes a really long time. On on MySQL.

    Read the article

  • Difference in output from use of synchronized keyword and join()

    - by user2964080
    I have 2 classes, public class Account { private int balance = 50; public int getBalance() { return balance; } public void withdraw(int amt){ this.balance -= amt; } } and public class DangerousAccount implements Runnable{ private Account acct = new Account(); public static void main(String[] args) throws InterruptedException{ DangerousAccount target = new DangerousAccount(); Thread t1 = new Thread(target); Thread t2 = new Thread(target); t1.setName("Ravi"); t2.setName("Prakash"); t1.start(); /* #1 t1.join(); */ t2.start(); } public void run(){ for(int i=0; i<5; i++){ makeWithdrawl(10); if(acct.getBalance() < 0) System.out.println("Account Overdrawn"); } } public void makeWithdrawl(int amt){ if(acct.getBalance() >= amt){ System.out.println(Thread.currentThread().getName() + " is going to withdraw"); try{ Thread.sleep(500); }catch(InterruptedException e){ e.printStackTrace(); } acct.withdraw(amt); System.out.println(Thread.currentThread().getName() + " has finished the withdrawl"); }else{ System.out.println("Not Enough Money For " + Thread.currentThread().getName() + " to withdraw"); } } } I tried adding synchronized keyword in makeWithdrawl method public synchronized void makeWithdrawl(int amt){ and I keep getting this output as many times I try Ravi is going to withdraw Ravi has finished the withdrawl Ravi is going to withdraw Ravi has finished the withdrawl Ravi is going to withdraw Ravi has finished the withdrawl Ravi is going to withdraw Ravi has finished the withdrawl Ravi is going to withdraw Ravi has finished the withdrawl Not Enough Money For Prakash to withdraw Not Enough Money For Prakash to withdraw Not Enough Money For Prakash to withdraw Not Enough Money For Prakash to withdraw Not Enough Money For Prakash to withdraw This shows that only Thread t1 is working... If I un-comment the the line saying t1.join(); I get the same output. So how does synchronized differ from join() ? If I don't use synchronize keyword or join() I get various outputs like Ravi is going to withdraw Prakash is going to withdraw Prakash has finished the withdrawl Ravi has finished the withdrawl Prakash is going to withdraw Ravi is going to withdraw Prakash has finished the withdrawl Ravi has finished the withdrawl Prakash is going to withdraw Ravi is going to withdraw Prakash has finished the withdrawl Ravi has finished the withdrawl Account Overdrawn Account Overdrawn Not Enough Money For Ravi to withdraw Account Overdrawn Not Enough Money For Prakash to withdraw Account Overdrawn Not Enough Money For Ravi to withdraw Account Overdrawn Not Enough Money For Prakash to withdraw Account Overdrawn So how does the output from synchronized differ from join() ?

    Read the article

  • INNER JOIN code calculated value with SELECT statement

    - by sp-1986
    I have the following stored procedure which will generate mon to sun and then creates a temp table with a series of 'weeks' (start and end weeks) : USE [test_staff] GO /****** Object: StoredProcedure [dbo].[sp_timesheets_all_staff_by_week_by_job_grouping_by_site] Script Date: 03/21/2012 09:04:49 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE PROCEDURE [dbo].[sp_timesheets_all_staff_by_week_by_job_grouping_by_site] ( @grouping_ref int, @week_ref int ) AS CREATE TABLE #WeeklyList ( Start_Week date, End_Week date, week_ref int --month_name date ) DECLARE @REPORT_DATE DATETIME, @WEEK_BEGINING VARCHAR(10) SELECT @REPORT_DATE = '2011-01-19T00:00:00' --SELECT @REPORT_DATE = GETDATE() -- should grab the date now. SELECT @WEEK_BEGINING = 'MONDAY' IF @WEEK_BEGINING = 'MONDAY' SET DATEFIRST 1 ELSE IF @WEEK_BEGINING = 'TUESDAY' SET DATEFIRST 2 ELSE IF @WEEK_BEGINING = 'WEDNESDAY' SET DATEFIRST 3 ELSE IF @WEEK_BEGINING = 'THURSDAY' SET DATEFIRST 4 ELSE IF @WEEK_BEGINING = 'FRIDAY' SET DATEFIRST 5 ELSE IF @WEEK_BEGINING = 'SATURDAY' SET DATEFIRST 6 ELSE IF @WEEK_BEGINING = 'SUNDAY' SET DATEFIRST 7 DECLARE @WEEK_START_DATE DATETIME, @WEEK_END_DATE DATETIME --GET THE WEEK START DATE SELECT @WEEK_START_DATE = @REPORT_DATE - (DATEPART(DW, @REPORT_DATE) - 1) --GET THE WEEK END DATE SELECT @WEEK_END_DATE = @REPORT_DATE + (7 - DATEPART(DW, @REPORT_DATE)) PRINT 'Week Start: ' + CONVERT(VARCHAR, @WEEK_START_DATE) PRINT 'Week End: ' + CONVERT(VARCHAR, @WEEK_END_DATE) DECLARE @Interval int = datediff(WEEK,getdate(),@WEEK_START_DATE)+1 --SELECT Start_Week=@WEEK_START_DATE --, End_Week=@WEEK_END_DATE --INTO #WeekList INSERT INTO #WeeklyList SELECT Start_Week=@WEEK_START_DATE, End_Week=@WEEK_END_DATE WHILE @Interval <= 0 BEGIN set @WEEK_START_DATE=DATEADD(WEEK,1,@WEEK_START_DATE) set @WEEK_END_DATE=DATEADD(WEEK,1,@WEEK_END_DATE) INSERT INTO #WeeklyList values (@WEEK_START_DATE,@WEEK_END_DATE) SET @Interval += 1; END SELECT CONVERT(VARCHAR(11), Start_Week, 106) AS 'month_name', CONVERT(VARCHAR(11), End_Week, 106) AS 'End', DATEDIFF(DAY, 0, Start_Week) / 7 AS week_ref -- create the unique week reference number --'VIEW' AS month_name FROM #WeeklyList In this section i am creating the week_ref DATEDIFF(DAY, 0, Start_Week) / 7 AS week_ref -- create the unique week reference number I then need to combine it with this select code: DECLARE @YearString char(3) = CONVERT(char(3), SUBSTRING(CONVERT(char(5), @week_ref), 1, 3)) DECLARE @MonthString char(2) = CONVERT(char(2), SUBSTRING(CONVERT(char(5), @week_ref), 4, 2)) --Convert: DECLARE @Year int = CONVERT(int, @YearString) + 1200 DECLARE @Month int = CONVERT(int, @MonthString) **--THIS FILTERS THE REPORT** SELECT ts.staff_member_ref, sm.common_name, sm.department_name, DATENAME(MONTH, ts.start_dtm) + ' ' + DATENAME(YEAR, ts.start_dtm) AS month_name, ts.timesheet_cat_ref, cat.desc_long AS timesheet_cat_desc, grps.grouping_ref, grps.description AS grouping_desc, ts.task_ref, tsks.task_code, tsks.description AS task_desc, ts.site_ref, sits.description AS site_desc, ts.site_ref AS Expr1, CASE WHEN ts .status = 0 THEN 'Pending' WHEN ts .status = 1 THEN 'Booked' WHEN ts .status = 2 THEN 'Approved' ELSE 'Invalid Status' END AS site_status, ts.booked_time AS booked_time_sum, start_dtm, CONVERT(varchar(20), start_dtm, 108) + ' ' + CONVERT(varchar(20), start_dtm, 103) AS start_dtm_text, booked_time, end_dtm, CONVERT(varchar(20), end_dtm, 108) + ' ' + CONVERT(varchar(20), end_dtm, 103) AS end_dtm_text FROM timesheets AS ts INNER JOIN timesheet_categories AS cat ON ts.timesheet_cat_ref = cat.timesheet_cat_ref INNER JOIN timesheet_tasks AS tsks ON ts.task_ref = tsks.task_ref INNER JOIN timesheet_task_groupings AS grps ON tsks.grouping_ref = grps.grouping_ref INNER JOIN timesheet_sites AS sits ON ts.site_ref = sits.site_ref INNER JOIN vw_staff_members AS sm ON ts.staff_member_ref = sm.staff_member_ref WHERE (ts.status IN (1, 2)) AND (cat.is_leave_category = 0) GROUP BY ts.staff_member_ref, sm.common_name, sm.department_name, DATENAME(MONTH, ts.start_dtm), DATENAME(YEAR, ts.start_dtm), ts.timesheet_cat_ref, cat.desc_long, grps.grouping_ref, grps.description, ts.status, ts.booked_time, ts.task_ref, tsks.task_code, tsks.description, ts.site_ref, sits.description, ts.start_dtm, ts.end_dtm ORDER BY sm.common_name, timesheet_cat_desc, tsks.task_code, site_desc DROP TABLE #WeeklyList GO I want to pass the week_ref into the SELECT statement (refer to comment - THIS FILTERS THE REPORT) but the problem is week_ref isnt a valid column as its derived by code. Any ideas?

    Read the article

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