Search Results

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

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

  • T-SQL - Left Outer Joins - Fileters in the where clause versus the on clause.

    - by Greg Potter
    I am trying to compare two tables to find rows in each table that is not in the other. Table 1 has a groupby column to create 2 sets of data within table one. groupby number ----------- ----------- 1 1 1 2 2 1 2 2 2 4 Table 2 has only one column. number ----------- 1 3 4 So Table 1 has the values 1,2,4 in group 2 and Table 2 has the values 1,3,4. I expect the following result when joining for Group 2: `Table 1 LEFT OUTER Join Table 2` T1_Groupby T1_Number T2_Number ----------- ----------- ----------- 2 2 NULL `Table 2 LEFT OUTER Join Table 1` T1_Groupby T1_Number T2_Number ----------- ----------- ----------- NULL NULL 3 The only way I can get this to work is if I put a where clause for the first join: PRINT 'Table 1 LEFT OUTER Join Table 2, with WHERE clause' select table1.groupby as [T1_Groupby], table1.number as [T1_Number], table2.number as [T2_Number] from table1 LEFT OUTER join table2 --****************************** on table1.number = table2.number --****************************** WHERE table1.groupby = 2 AND table2.number IS NULL and a filter in the ON for the second: PRINT 'Table 2 LEFT OUTER Join Table 1, with ON clause' select table1.groupby as [T1_Groupby], table1.number as [T1_Number], table2.number as [T2_Number] from table2 LEFT OUTER join table1 --****************************** on table2.number = table1.number AND table1.groupby = 2 --****************************** WHERE table1.number IS NULL Can anyone come up with a way of not using the filter in the on clause but in the where clause? The context of this is I have a staging area in a database and I want to identify new records and records that have been deleted. The groupby field is the equivalent of a batchid for an extract and I am comparing the latest extract in a temp table to a the batch from yesterday stored in a partioneds table, which also has all the previously extracted batches as well. Code to create table 1 and 2: create table table1 (number int, groupby int) create table table2 (number int) insert into table1 (number, groupby) values (1, 1) insert into table1 (number, groupby) values (2, 1) insert into table1 (number, groupby) values (1, 2) insert into table2 (number) values (1) insert into table1 (number, groupby) values (2, 2) insert into table2 (number) values (3) insert into table1 (number, groupby) values (4, 2) insert into table2 (number) values (4)

    Read the article

  • Partition Wise Joins II

    - by jean-pierre.dijcks
    One of the things that I did not talk about in the initial partition wise join post was the effect it has on resource allocation on the database server. When Oracle applies a different join method - e.g. not PWJ - what you will see in SQL Monitor (in Enterprise Manager) or in an Explain Plan is a set of producers and a set of consumers. The producers scan the tables in the the join. If there are two tables the producers first scan one table, then the other. The producers thus provide data to the consumers, and when the consumers have the data from both scans they do the join and give the data to the query coordinator. Now that behavior means that if you choose a degree of parallelism of 4 to run such query with, Oracle will allocate 8 parallel processes. Of these 8 processes 4 are producers and 4 are consumers. The consumers only actually do work once the producers are fully done with scanning both sides of the join. In the plan above you can see that the producers access table SALES [line 11] and then do a PX SEND [line 9]. That is the producer set of processes working. The consumers receive that data [line 8] and twiddle their thumbs while the producers go on and scan CUSTOMERS. The producers send that data to the consumer indicated by PX SEND [line 5]. After receiving that data [line 4] the consumers do the actual join [line 3] and give the data to the QC [line 2]. BTW, the myth that you see twice the number of processes due to the setting PARALLEL_THREADS_PER_CPU=2 is obviously not true. The above is why you will see 2 times the processes of the DOP. In a PWJ plan the consumers are not present. Instead of producing rows and giving those to different processes, a PWJ only uses a single set of processes. Each process reads its piece of the join across the two tables and performs the join. The plan here is notably different from the initial plan. First of all the hash join is done right on top of both table scans [line 8]. This query is a little more complex than the previous so there is a bit of noise above that bit of info, but for this post, lets ignore that (sort stuff). The important piece here is that the PWJ plan typically will be faster and from a PX process number / resources typically cheaper. You may want to look out for those plans and try to get those to appear a lot... CREDITS: credits for the plans and some of the info on the plans go to Maria, as she actually produced these plans and is the expert on plans in general... You can see her talk about explaining the explain plan and other optimizer stuff over here: ODTUG in Washington DC, June 27 - July 1 On the Optimizer blog At OpenWorld in San Francisco, September 19 - 23 Happy joining and hope to see you all at ODTUG and OOW...

    Read the article

  • How to perform Cross Join with Linq

    - by berthin
    Cross join consists to perform a Cartesian product of two sets or sequences. The following example shows a simple Cartesian product of the sets A and B: A (a1, a2) B (b1, b2) => C (a1 b1,            a1 b2,            a2 b1,            a2, b2 ) is the Cartesian product's result. Linq to Sql allows using Cross join operations. Cross join is not equijoin, means that no predicate expression of equality in the Join clause of the query. To define a cross join query, you can use multiple from clauses. Note that there's no explicit operator for the cross join. In the following example, the query must join a sequence of Product with a sequence of Pricing Rules: 1: //Fill the data source 2: var products = new List<Product> 3: { 4: new Product{ProductID="P01",ProductName="Amaryl"}, 5: new Product {ProductID="P02", ProductName="acetaminophen"} 6: }; 7:  8: var pricingRules = new List<PricingRule> 9: { 10: new PricingRule {RuleID="R_1", RuleType="Free goods"}, 11: new PricingRule {RuleID="R_2", RuleType="Discount"}, 12: new PricingRule {RuleID="R_3", RuleType="Discount"} 13: }; 14: 15: //cross join query 16: var crossJoin = from p in products 17: from r in pricingRules 18: select new { ProductID = p.ProductID, RuleID = r.RuleID };   Below the definition of the two entities using in the above example.   1: public class Product 2: { 3: public string ProductID { get; set; } 4: public string ProductName { get; set; } 5: } 1: public class PricingRule 2: { 3: public string RuleID { get; set; } 4: public string RuleType { get; set; } 5: }   Doing this: 1: foreach (var result in crossJoin) 2: { 3: Console.WriteLine("({0} , {1})", result.ProductID, result.RuleID); 4: }   The output should be similar on this:   ( P01   -    R_1 )   ( P01   -    R_2 )   ( P01   -    R_3 )   ( P02   -    R_1 )   ( P02   -    R_2 )   ( P02   -    R_3) Conclusion Cross join operation is useful when performing a Cartesian product of two sequences object. However, it can produce very large result sets that may caused a problem of performance. So use with precautions :)

    Read the article

  • JPA : optimize EJB-QL query involving large many-to-many join table

    - by Fabien
    Hi all. I'm using Hibernate Entity Manager 3.4.0.GA with Spring 2.5.6 and MySql 5.1. I have a use case where an entity called Artifact has a reflexive many-to-many relation with itself, and the join table is quite large (1 million lines). As a result, the HQL query performed by one of the methods in my DAO takes a long time. Any advice on how to optimize this and still use HQL ? Or do I have no choice but to switch to a native SQL query that would perform a join between the table ARTIFACT and the join table ARTIFACT_DEPENDENCIES ? Here is the problematic query performed in the DAO : @SuppressWarnings("unchecked") public List<Artifact> findDependentArtifacts(Artifact artifact) { Query query = em.createQuery("select a from Artifact a where :artifact in elements(a.dependencies)"); query.setParameter("artifact", artifact); List<Artifact> list = query.getResultList(); return list; } And the code for the Artifact entity : package com.acme.dependencytool.persistence.model; import java.util.ArrayList; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.Table; import javax.persistence.UniqueConstraint; @Entity @Table(name = "ARTIFACT", uniqueConstraints={@UniqueConstraint(columnNames={"GROUP_ID", "ARTIFACT_ID", "VERSION"})}) public class Artifact { @Id @GeneratedValue @Column(name = "ID") private Long id = null; @Column(name = "GROUP_ID", length = 255, nullable = false) private String groupId; @Column(name = "ARTIFACT_ID", length = 255, nullable = false) private String artifactId; @Column(name = "VERSION", length = 255, nullable = false) private String version; @ManyToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER) @JoinTable( name="ARTIFACT_DEPENDENCIES", joinColumns = @JoinColumn(name="ARTIFACT_ID", referencedColumnName="ID"), inverseJoinColumns = @JoinColumn(name="DEPENDENCY_ID", referencedColumnName="ID") ) private List<Artifact> dependencies = new ArrayList<Artifact>(); public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getGroupId() { return groupId; } public void setGroupId(String groupId) { this.groupId = groupId; } public String getArtifactId() { return artifactId; } public void setArtifactId(String artifactId) { this.artifactId = artifactId; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public List<Artifact> getDependencies() { return dependencies; } public void setDependencies(List<Artifact> dependencies) { this.dependencies = dependencies; } } Thanks in advance. EDIT 1 : The DDLs are generated automatically by Hibernate EntityMananger based on the JPA annotations in the Artifact entity. I have no explicit control on the automaticaly-generated join table, and the JPA annotations don't let me explicitly set an index on a column of a table that does not correspond to an actual Entity (in the JPA sense). So I guess the indexing of table ARTIFACT_DEPENDENCIES is left to the DB, MySQL in my case, which apparently uses a composite index based on both clumns but doesn't index the column that is most relevant in my query (DEPENDENCY_ID). mysql describe ARTIFACT_DEPENDENCIES; +---------------+------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +---------------+------------+------+-----+---------+-------+ | ARTIFACT_ID | bigint(20) | NO | MUL | NULL | | | DEPENDENCY_ID | bigint(20) | NO | MUL | NULL | | +---------------+------------+------+-----+---------+-------+ EDIT 2 : When turning on showSql in the Hibernate session, I see many occurences of the same type of SQL query, as below : select dependenci0_.ARTIFACT_ID as ARTIFACT1_1_, dependenci0_.DEPENDENCY_ID as DEPENDENCY2_1_, artifact1_.ID as ID1_0_, artifact1_.ARTIFACT_ID as ARTIFACT2_1_0_, artifact1_.GROUP_ID as GROUP3_1_0_, artifact1_.VERSION as VERSION1_0_ from ARTIFACT_DEPENDENCIES dependenci0_ left outer join ARTIFACT artifact1_ on dependenci0_.DEPENDENCY_ID=artifact1_.ID where dependenci0_.ARTIFACT_ID=? Here's what EXPLAIN in MySql says about this type of query : mysql explain select dependenci0_.ARTIFACT_ID as ARTIFACT1_1_, dependenci0_.DEPENDENCY_ID as DEPENDENCY2_1_, artifact1_.ID as ID1_0_, artifact1_.ARTIFACT_ID as ARTIFACT2_1_0_, artifact1_.GROUP_ID as GROUP3_1_0_, artifact1_.VERSION as VERSION1_0_ from ARTIFACT_DEPENDENCIES dependenci0_ left outer join ARTIFACT artifact1_ on dependenci0_.DEPENDENCY_ID=artifact1_.ID where dependenci0_.ARTIFACT_ID=1; +----+-------------+--------------+--------+-------------------+-------------------+---------+---------------------------------------------+------+-------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +----+-------------+--------------+--------+-------------------+-------------------+---------+---------------------------------------------+------+-------+ | 1 | SIMPLE | dependenci0_ | ref | FKEA2DE763364D466 | FKEA2DE763364D466 | 8 | const | 159 | | | 1 | SIMPLE | artifact1_ | eq_ref | PRIMARY | PRIMARY | 8 | dependencytooldb.dependenci0_.DEPENDENCY_ID | 1 | | +----+-------------+--------------+--------+-------------------+-------------------+---------+---------------------------------------------+------+-------+ EDIT 3 : I tried setting the FetchType to LAZY in the JoinTable annotation, but I then get the following exception : Hibernate: select artifact0_.ID as ID1_, artifact0_.ARTIFACT_ID as ARTIFACT2_1_, artifact0_.GROUP_ID as GROUP3_1_, artifact0_.VERSION as VERSION1_ from ARTIFACT artifact0_ where artifact0_.GROUP_ID=? and artifact0_.ARTIFACT_ID=? 51545 [btpool0-2] ERROR org.hibernate.LazyInitializationException - failed to lazily initialize a collection of role: com.acme.dependencytool.persistence.model.Artifact.dependencies, no session or session was closed org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.acme.dependencytool.persistence.model.Artifact.dependencies, no session or session was closed at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:380) at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationExceptionIfNotConnected(AbstractPersistentCollection.java:372) at org.hibernate.collection.AbstractPersistentCollection.readSize(AbstractPersistentCollection.java:119) at org.hibernate.collection.PersistentBag.size(PersistentBag.java:248) at com.acme.dependencytool.server.DependencyToolServiceImpl.createArtifactViewBean(DependencyToolServiceImpl.java:93) at com.acme.dependencytool.server.DependencyToolServiceImpl.createArtifactViewBean(DependencyToolServiceImpl.java:109) at com.acme.dependencytool.server.DependencyToolServiceImpl.search(DependencyToolServiceImpl.java:48) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at com.google.gwt.user.server.rpc.RPC.invokeAndEncodeResponse(RPC.java:527) at com.google.gwt.user.server.rpc.RemoteServiceServlet.processCall(RemoteServiceServlet.java:166) at com.google.gwt.user.server.rpc.RemoteServiceServlet.doPost(RemoteServiceServlet.java:86) at javax.servlet.http.HttpServlet.service(HttpServlet.java:637) at javax.servlet.http.HttpServlet.service(HttpServlet.java:717) at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:487) at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:362) at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216) at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:181) at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:729) at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:405) at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152) at org.mortbay.jetty.handler.RequestLogHandler.handle(RequestLogHandler.java:49) at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152) at org.mortbay.jetty.Server.handle(Server.java:324) at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:505) at org.mortbay.jetty.HttpConnection$RequestHandler.content(HttpConnection.java:843) at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:647) at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:205) at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:380) at org.mortbay.io.nio.SelectChannelEndPoint.run(SelectChannelEndPoint.java:395) at org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:488)

    Read the article

  • INNER JOIN syntax for mySQL using phpmyadmin

    - by David van Dugteren
    SELECT Question.userid, user.uid FROM `question` WHERE NOT `userid`=2 LIMIT 0, 60 INNER JOIN `user` ON `question`.userid=`user`.uid ORDER BY `question`.userid returns Error: 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 'INNER JOIN User ON question.userid=user.uid ORDER BY question.userid' at line 5 Can't for the life of me figure out what I'm doing wrong here.

    Read the article

  • self join- how to use the aggregate functions

    - by Ranjana
    self join- how to use the aggregate functions select a.tablename, b.TableName,b.UserName from Employee a inner join Employee b on a.ColumnValue=b.ColumnValue and and a.TableName <> b.TableName and a.UserName=b.UserName and also to check whether the same user has count of records i.e Employee a = count of records of Employee b. how to add count function over here

    Read the article

  • mysql count, distinct, join? COnfusion

    - by calum
    hello i have 2 tables: tblItems ID | orderID | productID 1 1 2 2 1 2 3 2 1 4 3 2 tblProducts productID | productName 1 ABC 2 DEF im attempting to find the most popular Product based on whats in "tblItems", and display the product Name and the number of times it appears in the tblItems table. i can get mysql to count up the total like: $sql="SELECT COUNT(productID) AS CountProductID FROM tblItems"; but i can't figure out how to join the products table on..if i try LEFT JOIN the query goes horribly wrong hopefully thats not too confusing..thankss

    Read the article

  • SQL join produces one result only

    - by Rami
    Can anyone please tell me why this result is generation only one results? taking in mind that everything is set right and the three tables are populated correctly, i took out the group_concat and it worked but of course with a php undefined index error! SELECT `songs`.`song_name`, `songs`.`add_date`, `songs`.`song_id`, `songs`.`song_picture`, group_concat(DISTINCT artists.artist_name) as artist_name FROM (`songs`) JOIN `mtm_songs_artists` ON `songs`.`song_id` = `mtm_songs_artists`.`song_id` JOIN `artists` ON `artists`.`artist_id` = `mtm_songs_artists`.`artist_id` ORDER BY `songs`.`song_id` DESC LIMIT 10 so i'm guessing it's something related to group_concat. best regards, Rami

    Read the article

  • join two table for insert data in database in android

    - by shadi
    I have two table(t1,t2) in android, t1 has a primary key that it is foreign key for t2,i want to insert data to this tables,is it necessary to join these two table?if yes, what is code for join these table? i insert data in one of them like this: public long insertQuote(String Quote,int Count1 ) { ContentValues initialValues = new ContentValues(); initialValues.put(GoodName, Quote); initialValues.put(CartID, Count1); return db.insert(DATABASE_TABLE, null, initialValues); }

    Read the article

  • web application , join event on facebook using php api

    - by Mohammed Al-shareif
    enter code herei created my events on facebook throw php api (form my website) ...every thing its fine with me and the events appear 100% on FB calendar , i got the FB event id and save to my db , enter code here my users can join the same event on my website i need them to join the same event on facebook also i have the facebook event id , and user accept my permission to access his/here calendar please anybody help!!!

    Read the article

  • Appending a prefix when using join in Perl

    - by syker
    I have an array of strings that I would like to use the join function on. However, I would like to prefix each string with the same string. Can I do this in one line as opposed to iterating through the array first and changing each value before using join?

    Read the article

  • entity framework join

    - by Luca Romagnoli
    Hi, i have 2 table (user, user_profile) without a explicit relationship in the sql db. and i can't add it to the db. so, i can't do this: db.user.include("user_profile") the attribute in for the join is user_id is possible do anything like this? db.user.join("user_profile On user.id = user_profile.user_id") How can i do that? thanks

    Read the article

  • Data retrieval and Join operations with cluster db server

    - by Goerge
    If any database spreads across multiple servers (ex. Microsoft Sql Server), how can we do join or filter operations. In my scenario, if suppose: A single table spreads across multiple servers how can we filter rows based on user input? If master table is there on one db server and transaction table is at another db server, how can we do join operations? Please let me know how can we achieve this and where can I get more details about this?

    Read the article

  • Python: Split, strip, and join in one line

    - by PandemoniumSyndicate
    I'm curious if their is some python magic I may not know to accomplish a bit of frivolity given the line: csvData.append(','.join([line.split(":").strip() for x in L])) I'm attempting to split a line on :, trim whitespace around it, and join on , problem is, since the array is returned from line.split(":"), the for x in L #<== L doesn't exist! causes issues since I have no name for the array returned by line.split(":") So I'm curious if there is a sexy piece of syntax I could use to accomplish this in one shot? Cheers!

    Read the article

  • MySQL: Use CASE/ELSE value as join parameter

    - by DRJ
    I'm trying to join the NAME and PHOTO from USERS table to the TRANSACTIONS table based on who is the payer or payee. It keeps telling me can't find the table this -- What am I doing wrong? SELECT name,photo,amount,comment, ( CASE payer_id WHEN 72823 THEN payee_id ELSE payer_id END ) AS this FROM transactions RIGHT JOIN users ON (users.id=this) WHERE payee_id=72823 OR payer_id=72823

    Read the article

  • Join two results in Powershell

    - by Hinek
    I've got two CMDlets that return lists of objects. One returns objects of the type SPSolution, which contains the property Id, the other returns objects of the type SPFeature with a property SolutionId. Now I want to join/merge this data something like this: $f = Get-Feature $s = Get-Solution $result = <JOIN> $f $s <ON> $f.SolutionId = $s.Id <SELECT> FeatureName = $f.DisplayName, SolutionName = $s.Name

    Read the article

  • Complex multiple join query across 3 tables

    - by Keir Simmons
    I have 3 tables: shops, PRIMARY KEY cid,zbid shop_items, PRIMARY KEY id shop_inventory, PRIMARY KEY id shops a is related to shop_items b by the following: a.cid=b.cid AND a.zbid=b.szbid shops is not directly related to shop_inventory shop_items b is related to shop_inventory c by the following: b.cid=c.cid AND b.id=c.iid Now, I would like to run a query which returns a.* (all columns from shops). That would be: SELECT a.* FROM shops a WHERE a.cid=1 AND a.zbid!=0 Note that the WHERE clause is necessary. Next, I want to return the number of items in each shop: SELECT a.*, COUNT(b.id) items FROM shops a LEFT JOIN shop_items b ON b.cid=a.cid AND b.szbid=a.zbid WHERE a.cid=1 GROUP BY b.szbid,b.cid As you can see, I have added a GROUP BY clause for this to work. Next, I want to return the average price of each item in the shop. This isn't too hard: SELECT a.*, COUNT(b.id) items, AVG(COALESCE(b.price,0)) average_price FROM shops a LEFT JOIN shop_items b ON b.cid=a.cid AND b.szbid=a.zbid WHERE a.cid=1 GROUP BY b.szbid,b.cid My next criteria is where it gets complicated. I also want to return the unique buyers for each shop. This can be done by querying shop_inventory c, getting the COUNT(DISTINCT c.zbid). Now remember how these tables are related; this should only be done for the rows in c which relate to an item in b which is owned by the respective shop, a. I tried doing the following: SELECT a.*, COUNT(b.id) items, AVG(COALESCE(b.price,0)) average_price, COUNT(DISTINCT c.zbid) FROM shops a LEFT JOIN shop_items b ON b.cid=a.cid AND b.szbid=a.zbid LEFT JOIN shop_inventory c ON c.cid=b.cid AND c.iid=b.id WHERE a.cid=1 GROUP BY b.szbid,b.cid However, this did not work as it messed up the items value. What is the proper way to achieve this result? I also want to be able to return the total number of purchases made in each shop. This would be done by looking at shop_inventory c and adding up the c.quantity value for each shop. How would I add that in as well?

    Read the article

  • SQL joins "going up" two tables

    - by blcArmadillo
    I'm trying to create a moderately complex query with joins: SELECT `history`.`id`, `parts`.`type_id`, `serialized_parts`.`serial`, `history_actions`.`action`, `history`.`date_added` FROM `history_actions`, `history` LEFT OUTER JOIN `parts` ON `parts`.`id` = `history`.`part_id` LEFT OUTER JOIN `serialized_parts` ON `serialized_parts`.`parts_id` = `history`.`part_id` WHERE `history_actions`.`id` = `history`.`action_id` AND `history`.`unit_id` = '1' ORDER BY `history`.`id` DESC I'd like to replace `parts`.`type_id` in the SELECT statement with `part_list`.`name` where the relationship I need to enforce between the two tables is `part_list`.`id` = `parts`.`type_id`. Also I have to use joins because in some cases `history`.`part_id` may be NULL which obviously isn't a valid part id. How would I modify the query to do this?

    Read the article

  • MySQL join headaches, please help!

    - by Andrew Heath
    Ok, I've hit the wall here and need some help. Sample tables are as follows: SCENARIO_NATIONS [scenID] [side] [nation] scen001 1 Germany scen001 2 Britain scen001 2 Canada SCENARIO_NEEDUNITS [scenID] [unitID] scen001 0001 scen001 0003 scen001 0107 scen001 0258 scen001 0759 UNIT_BASIC_DATA [unitID] [nation] [name] 0001 Germany Mortars 0003 Germany Infantry 0107 Britain Lt 0258 Britain Infantry 0759 Canada Kilted Yaksmen Goal: given a scenID, pull a list of units from the database sorted by side, nation, name. I can do everything except for the side inclusion with: SELECT scenario_needunits.scenID, unit_basic_data.nation, unit_basic_data.name FROM scenario_needunits LEFT OUTER JOIN unit_basic_data ON scenario_needunits.unitID=unit_basic_data.unitID WHERE scenario_needunits.scenID='scen001' ORDER BY unit_basic_data.nation ASC, unit_basic_data.name ASC I've tried just dropping the SCENARIO_NATIONS table in as a LEFT OUTER JOIN on scenID but what ends up happening is that ALL units come back with a side of 1 because that's always the first side listed for the scenID in the SCENARIO_NATIONS table. Conceptually, what I think needs to happen is SCENARIO_NATIONS must be joined to both the scenID (to restrict it to just that scenario) and to each unit's nation but I don't have any idea how to do that and my Google-fu is inadequate. :-/

    Read the article

  • LINQ Joins - Performance

    - by Meiscooldude
    I am curious on how exactly LINQ (not LINQ to SQL) is performing is joins behind the scenes in relation to how Sql Server performs joins. Sql Server before executing a query, generates an Execution Plan. The Execution Plan is basically an Expression Tree on what it believes is the best way to execute the query. Each node provides information on whether to do a Sort, Scan, Select, Join, ect. On a 'Join' node in our execution plan, we can see three possible algorithms; Hash Join, Merge Join, and Nested Loops Join. Sql Server will choose which algorithm to for each Join operation based on expected number of rows in Inner and Outer tables, what type of join we are doing (some algorithms don't support all types of joins), whether we need data ordered, and probably many other factors. Join Algorithms: Nested Loop Join: Best for small inputs, can be optimized with ordered inner table. Merge Join: Best for medium to large inputs sorted inputs, or an output that needs to be ordered. Hash Join: Best for medium to large inputs, can be parallelized to scale linearly. LINQ Query: DataTable firstTable, secondTable; ... var rows = from firstRow in firstTable.AsEnumerable () join secondRow in secondTable.AsEnumerable () on firstRow.Field<object> (randomObject.Property) equals secondRow.Field<object> (randomObject.Property) select new {firstRow, secondRow}; SQL Query: SELECT * FROM firstTable fT INNER JOIN secondTable sT ON fT.Property = sT.Property Sql Server might use a Nested Loop Join if it knows there are a small number of rows from each table, a merge join if it knows one of the tables has an index, and Hash join if it knows there are a lot of rows on either table and neither has an index. Does Linq choose its algorithm for joins? or does it always use one?

    Read the article

  • showing null rows using join

    - by Pradyut Bhattacharya
    Hi, In mysql i m selecting from a table shouts having a foreign key to another table named "roleuser" with the matching column as user_id Now the user_id column in the shouts table for some rows is null (not actually null but with no inserts in mysql) How to show all the rows of the shouts table either with user_id null or not I m executing the sql statement SELECT s.*, r.firstname, r.lastname FROM shouts s left join roleuser r where r.user_id = s.user_id limit 50; which does not executes and shows 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 'where r.user_id = s.user_id limit 50' at line 2 but using inner join the sql executes which shows rows which only have user_id values in the shouts table. the nulls are not shown. SELECT s.*, r.firstname, r.lastname FROM shouts s inner join roleuser r where r.user_id = s.user_id limit 50; How can i show all the rows from the shouts table and null values in the firstname and lastname columns where the user_id is null in the shouts table. If not at all possible with sql may be using stored procedures... Thanks Pradyut

    Read the article

  • Problem with duplicates in a SQL Join

    - by Chris Ballance
    I have the following result set from a join of three tables, an articles table, a products table, an articles to products mapping table. I would like to have the results with duplicates removed similar to a select distinct on content id. Current result set: [ContendId] [Title] [productId] 1 article one 2 1 article one 3 1 article one 9 4 article four 1 4 article four 10 4 article four 14 5 article five 1 6 article six 8 6 article six 10 6 article six 11 6 article six 13 7 article seven 14 Desired result set: [ContendId] [Title] [productId] 1 article one * 4 article four * 5 article five * 6 article six * 7 article seven * Here is condensed example of the relevant SQL: IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'tempdb.dbo.products') AND type = (N'U')) drop table tempdb.dbo.products go CREATE TABLE tempdb.dbo.products ( productid int, productname varchar(255) ) go IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'articles') AND type = (N'U')) drop table tempdb.dbo.articles go create table tempdb.dbo.articles ( contentid int, title varchar(255) ) IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'articles') AND type = (N'U')) drop table tempdb.dbo.articles go create table tempdb.dbo.articles ( contentid int, title varchar(255) ) IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'articleproducts') AND type = (N'U')) drop table tempdb.dbo.articleproducts go create table tempdb.dbo.articleproducts ( contentid int, productid int ) insert into tempdb.dbo.products values (1,'product one'), (2,'product two'), (3,'product three'), (4,'product four'), (5,'product five'), (6,'product six'), (7,'product seven'), (8,'product eigth'), (9,'product nine'), (10,'product ten'), (11,'product eleven'), (12,'product twelve'), (13,'product thirteen'), (14,'product fourteen') insert into tempdb.dbo.articles VALUES (1,'article one'), (2, 'article two'), (3, 'article three'), (4, 'article four'), (5, 'article five'), (6, 'article six'), (7, 'article seven'), (8, 'article eight'), (9, 'article nine'), (10, 'article ten') INSERT INTO tempdb.dbo.articleproducts VALUES (1,2), (1,3), (1,9), (4,1), (4,10), (4,14), (5,1), (6,8), (6,10), (6,11), (6,13), (7,14) GO select DISTINCT(a.contentid), a.title, p.productid from articles a JOIN articleproducts ap ON a.contentid = ap.contentid JOIN products p ON a.contentid = ap.contentid AND p.productid = ap.productid ORDER BY a.contentid

    Read the article

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