Search Results

Search found 6276 results on 252 pages for 'join'.

Page 22/252 | < Previous Page | 18 19 20 21 22 23 24 25 26 27 28 29  | Next Page >

  • Which is faster join

    - by Costa
    Hi Which is faster SELECT * FROM X INNER JOIN Y ON x.Record_ID = y.ForignKey_NotIndexed_NotUnique or SELECT * FROM X INNER JOIN Y ON y.ForignKey_NotIndexed_NotUnique = x.Record_ID

    Read the article

  • I’m screwing up this LEFT JOIN

    - by Jason Shultz
    I'm doing a left join on several tables. What I want to happen is that it list all the businesses. Then, it looks through the photos, videos, specials and categories. IF there are photos, then the tables shows yes, if there are videos, it shows yes in the table. It does all that without any problems. Except for one thing. For every photo, it shows the business that many times. For example, if there are 5 photos in the DB for a business, it shows the business five times. Obviously, this is not what I want to happen. Can you help? function frontPageList() { $this->db->select('b.id, b.busname, b.busowner, b.webaddress, p.thumb, v.title, c.catname'); $this->db->from ('business AS b'); $this->db->where('b.featured', '1'); $this->db->join('photos AS p', 'p.busid = b.id', 'left'); $this->db->join('video AS v', 'v.busid = b.id', 'left'); $this->db->join('specials AS s', 's.busid = b.id', 'left'); $this->db->join('category As c', 'b.category = c.id', 'left'); return $this->db->get();

    Read the article

  • Joining H264 *without* re-encoding

    - by jdmuys
    Hi, I have two halves of a single show in two .MP4 files, encoded in H264. I would like to join them without re-encoding. Is this possible? I managed to create a joined video as a Quicktime file (.mov) using Quicktime Pro, but then Quicktime Pro will not convert it back to .MP4 without re-encoding. This may be because looking inside the .mov file, the two H264 videos are in there still separated as individual "objects". I am also struggling with MPEG StreamClip without reaching a real solution. But I may have missed something. Note that I have the same issue with MPEG2 files. I can export them to a .MPEG container or a .TS file for example, but I don't know how to join them without re-encoding. Any suggestion welcome, preferably using Mac software.

    Read the article

  • joining text files with 600M+ lines

    - by dnkb
    I have two files huge.txt and small.txt. Huge has around 600M rows and it's 14Gigs, each line has four space separated words (tokens) and finally another space separated column with a number. Small has 150K rows with a size of ~3M, a space separated word and a number. Both Files are sorted using the sort command, with no extra options. The words in both files may include apostrophes (') and dashes (-). The deisred output would contain all columns from the huge.txt and the second column (the number) from small txt where the first word of huge.txt and the first word of small.txt match. My attemtpts below failed miserably with the following error: cat huge.txt|join -o 1.1 1.2 1.3 1.4 2.2 - small.txt > output.txt join: memory exhausted What I suspect is that the sorting order isn't right somehow even though the files are pre-sorted using: sort -k1 huge.unsorted.txt > huge.txt sort -k1 small.unsorted.txt > small.txt Problems seem to appear around words that have apostrophes (') or dashes (-). I also tried dictinoary sorting using the -d option bumping into the same error at the end. I see two ways out of this but don't know how to implement any of them. 1) Any tips how to sort the files in a way that the join command considers them to be sorted properly? 2) I was thinking of calculating MD5 or some other hashes of the strings to get rid of the apostrophes and dashes, and do the sorting and joining with the hashes instead of the strings themselves an dat the "translate" back the hashes to strings, but leave the numbers intact at the end of the lines. Since there would be only 150K hashes it's not that bad. What would be a good way to calculate individual hashes for each of the strings? Some AWK magic? See file samples at the end. Thank you! sample of huge.txt had stirred me to 46 had stirred my corruption 57 had stirred old emotions 55 had stirred something in 69 had stirred something within 40 sample of small.txt caley 114881 calf 2757974 calfed 137861 calfee 71143 calflora 154624 calfskin 148347 calgary 9416465 calgon's 94846

    Read the article

  • Cross join problem query

    - by user66121
    i have following table structure HUB_DETAILS (Master) Branch_ID Branch_Name VTRCheckList (Master) CLid CLName VTRCheckListDetails (Detail) CLid Branch_ID VTRValue vtrRespDate Actually when i run the following query it does comes with all the Checklist names alongwith all branch names but shows the value in every branch infact only 1 branch has data in the given date criteria. it should show 0 if there is no data in checklist of the respective branch. SELECT VTRCheckList.CLName, Hub_Details.BranchName, sum(cast(VTRCheckListDetails.VtrValue as int)) as 'Total' FROM VTRCheckListDetails INNER JOIN VTRCheckList ON VTRCheckListDetails.CLid = VTRCheckList.CLid CROSS JOIN Hub_Details where Convert(date,VTRCheckListDetails.vtrRespDate, 105) >= convert(date,'01-01-2011',105) and Convert(date, VTRCheckListDetails.vtrRespDate, 105) <= convert(date,'30-01-2011',105) GROUP BY VTRCheckList.CLName, Hub_Details.BranchName

    Read the article

  • Cakephp beforeFind() - How do I add a JOIN condition AFTER the belongsTo association is added?

    - by michael
    I'm in Model-beforeFind($queryData), trying to add a JOIN condition to the queryData on a model which has belongsTo associations. Unfortunately, the new JOIN references a table in the belongsTo association, so it must appear AFTER the belongsTo in the query. Here is my Tagged-belongsTo association: app\plugins\tags\models\tagged.php (line 192) Array ( [Tag] => Array ( [className] => Tag [foreignKey] => tag_id [conditions] => [fields] => [order] => [counterCache] => ) [Group] => Array ( [className] => Group [foreignKey] => foreign_key [conditions] => Array ( [Tagged.model] => Group ) [fields] => [order] => [counterCache] => ) ) Here is the JOIN added in Tagged-beforeFind(), notice that the belongsTo joins have not yet been added: app\plugins\tags\models\tagged.php (line 194) Array ( [conditions] => Array ( [Tag.keyname] => europe ) [fields] => Array ( [0] => DISTINCT Group.* [1] => GroupPermission.* ) [joins] => Array ( [0] => Array ( [table] => permissions [alias] => GroupPermission [foreignKey] => [type] => INNER [conditions] => Array ( [GroupPermission.model] => Group [0] => GroupPermission.foreignId = Group.id [or] => Array ( ... ) ) ) ) [limit] => [offset] => [order] => Array ( [0] => ) [page] => 1 [group] => [callbacks] => 1 [by] => europe [model] => Group ) When I check the output, it fails with "1054: Unknown column 'Group.id' in 'on clause'" because the Permissions join appeared BEFORE the Groups join. SELECT DISTINCT `Group`.*, `GroupPermission`.* FROM `tagged` AS `Tagged` INNER JOIN permissions AS `GroupPermission` ON (`GroupPermission`.`model` = 'Group' AND `GroupPermission`.`foreignId` = `Group`.`id` AND (...)) LEFT JOIN `tags` AS `Tag` ON (`Tagged`.`tag_id` = `Tag`.`id`) LEFT JOIN `groups` AS `Group` ON (`Tagged`.`foreign_key` = `Group`.`id` AND `Tagged`.`model` = 'Group') WHERE `Tag`.`keyname` = 'europe' But this SQL (with Permissions joined moved to the end) works fine: SELECT DISTINCT `Group`.*, `GroupPermission`.* FROM `tagged` AS `Tagged` LEFT JOIN `tags` AS `Tag` ON (`Tagged`.`tag_id` = `Tag`.`id`) LEFT JOIN `groups` AS `Group` ON (`Tagged`.`foreign_key` = `Group`.`id` AND `Tagged`.`model` = 'Group') INNER JOIN permissions AS `GroupPermission` ON (`GroupPermission`.`model` = 'Group' AND `GroupPermission`.`foreignId` = `Group`.`id` AND (...)) WHERE `Tag`.`keyname` = 'europe' How do I add my join in beforeFind() after the belongsTo join?

    Read the article

  • multple inner joins 3 or more crashes mysql server 5.1.30 opensolaris

    - by user331849
    when doing simple query on 4 inner joined tables, the server crashes with the output below appearing in the the mysql .err file. eg. select * from table1 inner join table2 on table1.a = table2.a and table1.b = table2.b inner join table3 on table2.a = table3.a and table2.c = table3.c inner join table4 on table3.a = table4.a and table3.d = table4.d If i remove one of the tables it executes fine. Likewise if I remove a different table, it executes fine. Though all tables have been checked anyway, this would suggest that it is not a problem specifically with one of the tables. mysql.err trace: 100503 18:13:19 - mysqld got signal 11 ; This could be because you hit a bug. It is also possible that this binary or one of the libraries it was linked against is corrupt, improperly built, or misconfigured. This error can also be caused by malfunctioning hardware. We will try our best to scrape up some info that will hopefully help diagnose the problem, but since we have already crashed, something is definitely wrong and this may fail. key_buffer_size=1572864000 read_buffer_size=2097152 max_used_connections=11 max_threads=151 threads_connected=10 It is possible that mysqld could use up to key_buffer_size + (read_buffer_size + sort_buffer_size)*max_threads = 2155437 K bytes of memory Hope that's ok; if not, decrease some variables in the equation. thd: 0x72febda8 Attempting backtrace. You can use the following information to find out where mysqld died. If you see no messages after this, something went terribly wrong... stack_bottom = fe07efb0 thread_stack 0x40000 Trying to get some variables. Some pointers may be invalid and cause the dump to abort... thd-query at be1021f0 = explain select * from business inner join timetable on business.id = timetable.business_id inner join timetableentry on timetable.business_id = timetableentry.business_id and timetable.kid = timetableentry.parent inner join staff on timetable.business_id = staff.business_id and timetable.staf f_person = staff.kid where business.id = '3050bb04fda41df64a9c1c149150026c' thd-thread_id=9 thd-killed=NOT_KILLED The manual page at http://dev.mysql.com/doc/mysql/en/crashing.html contains information that should help you find out what is causing the crash. 100503 18:13:19 mysqld_safe mysqld restarted 100503 18:13:20 InnoDB: Failed to set DIRECTIO_ON on file ./ibdata1: OPEN: Inap propriate ioctl for device, continuing anyway 100503 18:13:20 InnoDB: Failed to set DIRECTIO_ON on file ./ibdata1: OPEN: Inap propriate ioctl for device, continuing anyway InnoDB: The log sequence number in ibdata files does not match InnoDB: the log sequence number in the ib_logfiles! 100503 18:13:20 InnoDB: Database was not shut down normally! InnoDB: Starting crash recovery. InnoDB: Reading tablespace information from the .ibd files... InnoDB: Restoring possible half-written data pages from the doublewrite InnoDB: buffer... InnoDB: Last MySQL binlog file position 0 2731, file name ./mysql-bin.000093 100503 18:13:20 InnoDB: Started; log sequence number 0 2650338426 100503 18:13:20 [Note] Recovering after a crash using mysql-bin 100503 18:13:20 [Note] Starting crash recovery... 100503 18:13:20 [Note] Crash recovery finished. This on opensolaris SunOS 5.11 snv_111b i86pc i386 i86pc Mysql 5.1.30 Here is a snippet from the my.cnf file: key_buffer = 1500M max_allowed_packet = 1M thread_stack = 256K thread_cache_size = 8 sort_buffer_size = 2M read_buffer_size = 2M read_rnd_buffer_size = 8M table_cache = 512 tmp_table_size = 400M max_heap_table_size = 64M query_cache_limit = 20M query_cache_size = 200M Is this a bug or a configuration issue?

    Read the article

  • Joins in LINQ to SQL

    - by rajbk
    The following post shows how to write different types of joins in LINQ to SQL. I am using the Northwind database and LINQ to SQL for these examples. NorthwindDataContext dataContext = new NorthwindDataContext(); Inner Join var q1 = from c in dataContext.Customers join o in dataContext.Orders on c.CustomerID equals o.CustomerID select new { c.CustomerID, c.ContactName, o.OrderID, o.OrderDate }; SELECT [t0].[CustomerID], [t0].[ContactName], [t1].[OrderID], [t1].[OrderDate]FROM [dbo].[Customers] AS [t0]INNER JOIN [dbo].[Orders] AS [t1] ON [t0].[CustomerID] = [t1].[CustomerID] Left Join var q2 = from c in dataContext.Customers join o in dataContext.Orders on c.CustomerID equals o.CustomerID into g from a in g.DefaultIfEmpty() select new { c.CustomerID, c.ContactName, a.OrderID, a.OrderDate }; SELECT [t0].[CustomerID], [t0].[ContactName], [t1].[OrderID] AS [OrderID], [t1].[OrderDate] AS [OrderDate]FROM [dbo].[Customers] AS [t0]LEFT OUTER JOIN [dbo].[Orders] AS [t1] ON [t0].[CustomerID] = [t1].[CustomerID] Inner Join on multiple //We mark our anonymous type properties as a and b otherwise//we get the compiler error "Type inferencce failed in the call to 'Join’var q3 = from c in dataContext.Customers join o in dataContext.Orders on new { a = c.CustomerID, b = c.Country } equals new { a = o.CustomerID, b = "USA" } select new { c.CustomerID, c.ContactName, o.OrderID, o.OrderDate }; SELECT [t0].[CustomerID], [t0].[ContactName], [t1].[OrderID], [t1].[OrderDate]FROM [dbo].[Customers] AS [t0]INNER JOIN [dbo].[Orders] AS [t1] ON ([t0].[CustomerID] = [t1].[CustomerID]) AND ([t0].[Country] = @p0) Inner Join on multiple with ‘OR’ clause var q4 = from c in dataContext.Customers from o in dataContext.Orders.Where(a => a.CustomerID == c.CustomerID || c.Country == "USA") select new { c.CustomerID, c.ContactName, o.OrderID, o.OrderDate }; SELECT [t0].[CustomerID], [t0].[ContactName], [t1].[OrderID], [t1].[OrderDate]FROM [dbo].[Customers] AS [t0], [dbo].[Orders] AS [t1]WHERE ([t1].[CustomerID] = [t0].[CustomerID]) OR ([t0].[Country] = @p0) Left Join on multiple with ‘OR’ clause var q5 = from c in dataContext.Customers from o in dataContext.Orders.Where(a => a.CustomerID == c.CustomerID || c.Country == "USA").DefaultIfEmpty() select new { c.CustomerID, c.ContactName, o.OrderID, o.OrderDate }; SELECT [t0].[CustomerID], [t0].[ContactName], [t1].[OrderID] AS [OrderID], [t1].[OrderDate] AS [OrderDate]FROM [dbo].[Customers] AS [t0]LEFT OUTER JOIN [dbo].[Orders] AS [t1] ON ([t1].[CustomerID] = [t0].[CustomerID]) OR ([t0].[Country] = @p0)

    Read the article

  • Need help with joins in sqlalchemy

    - by Steve
    I'm new to Python, as well as SQL Alchemy, but not the underlying development and database concepts. I know what I want to do and how I'd do it manually, but I'm trying to learn how an ORM works. I have two tables, Images and Keywords. The Images table contains an id column that is its primary key, as well as some other metadata. The Keywords table contains only an id column (foreign key to Images) and a keyword column. I'm trying to properly declare this relationship using the declarative syntax, which I think I've done correctly. Base = declarative_base() class Keyword(Base): __tablename__ = 'Keywords' __table_args__ = {'mysql_engine' : 'InnoDB'} id = Column(Integer, ForeignKey('Images.id', ondelete='CASCADE'), primary_key=True) keyword = Column(String(32), primary_key=True) class Image(Base): __tablename__ = 'Images' __table_args__ = {'mysql_engine' : 'InnoDB'} id = Column(Integer, primary_key=True, autoincrement=True) name = Column(String(256), nullable=False) keywords = relationship(Keyword, backref='image') This represents a many-to-many relationship. One image can have many keywords, and one keyword can relate back to many images. I want to do a keyword search of my images. I've tried the following with no luck. Conceptually this would've been nice, but I understand why it doesn't work. image = session.query(Image).filter(Image.keywords.contains('boy')) I keep getting errors about no foreign key relationship, which seems clearly defined to me. I saw something about making sure I get the right 'join', and I'm using 'from sqlalchemy.orm import join', but still no luck. image = session.query(Image).select_from(join(Image, Keyword)).\ filter(Keyword.keyword == 'boy') I added the specific join clause to the query to help it along, though as I understand it, I shouldn't have to do this. image = session.query(Image).select_from(join(Image, Keyword, Image.id==Keyword.id)).filter(Keyword.keyword == 'boy') So finally I switched tactics and tried querying the keywords and then using the backreference. However, when I try to use the '.images' iterating over the result, I get an error that the 'image' property doesn't exist, even though I did declare it as a backref. result = session.query(Keyword).filter(Keyword.keyword == 'boy').all() I want to be able to query a unique set of image matches on a set of keywords. I just can't guess my way to the syntax, and I've spent days reading the SQL Alchemy documentation trying to piece this out myself. I would very much appreciate anyone who can point out what I'm missing.

    Read the article

  • Joining the same model twice in a clean way, but making the code reusable

    - by Shako
    I have a model Painting which has a Paintingtitle in each language and a Paintingdescription in each language: class Painting < ActiveRecord::Base has_many :paintingtitles, :dependent => :destroy has_many :paintingdescriptions, :dependent => :destroy end class Paintingtitle < ActiveRecord::Base belongs_to :painting belongs_to :language end class Paintingdescription < ActiveRecord::Base belongs_to :painting belongs_to :language end class Language < ActiveRecord::Base has_many :paintingtitles, :dependent => :nullify has_many :paintingdescriptions, :dependent => :nullify has_many :paintings, :through => :paintingtitles end As you might notice, I reference the Language model from my Painting model via both the Paintingtitle model and Paintingdescription model. This works for me when getting a list of paintings with their title and description in a specific language: cond = {"paintingdescription_languages.code" => language_code, "paintingtitle_languages.code" => language_code} cond['paintings.publish'] = 1 unless admin paginate( :all, :select => ["paintings.id, paintings.publish, paintings.photo_file_name, paintingtitles.title, paintingdescriptions.description"], :joins => " INNER JOIN paintingdescriptions ON (paintings.id = paintingdescriptions.painting_id) INNER JOIN paintingtitles ON (paintings.id = paintingtitles.painting_id) INNER JOIN languages paintingdescription_languages ON (paintingdescription_languages.id = paintingdescriptions.language_id) INNER JOIN languages paintingtitle_languages ON (paintingtitle_languages.id = paintingtitles.language_id) ", :conditions => cond, :page => page, :per_page => APP_CONFIG['per_page'], :order => "id DESC" ) Now I wonder if this is a correct way of doing this. I need to fetch paintings with their title and description in different functions, but I don't want to specify this long join statement each time. Is there a cleaner way, for instance making use of the has_many through? e.g. has_many :paintingdescription_languages, :through => :paintingdescriptions, :source => :language has_many :paintingtitle_languages, :through => :paintingtitles, :source => :language But if I implement above 2 lines together with the following ones, then only paintingtitles are filtered by language, and not the paintingdescriptions: cond = {"languages.code" => language_code} cond['paintings.publish'] = 1 unless admin paginate( :all, :select => ["paintings.id, paintings.publish, paintings.photo_file_name, paintingtitles.title, paintingdescriptions.description"], :joins => [:paintingdescription_languages, :paintingtitle_languages], :conditions => cond, :page => page, :per_page => APP_CONFIG['per_page'], :order => "id DESC" )

    Read the article

  • Join Domain from VM

    - by Adis
    I have two VMs running on VMWare Player. I use NAT adapter settings. The host machine for VMs is running on corporate network. First VM has Domain controller running and I can log in on that machine using domain credentials. I named domain wm.local When I run IP config on this machine: IP: 192.168.87.132 Def Gataway: 192.168.87.2 DNS server: 192.168.87.2 DHCP server: 192.168.87.254 Second VM cannot join domain. When I try it with domain WM I'm propmted for credentials. And I enter Administrator credentials and than it waits for some time and I get response: "The specified domain either does not exist or could not be contacted" If i type wm.local as domain when trying to join it does not prompt me to login but just shows "An Active Directory Domain Controller (AD DC) for the domain wm.local could not be contacted. And here it takes no time to get this error message. Ipconfig on this machine: IP: 192.168.87.134 Def Gataway: 192.168.87.2 DNS server: 192.168.87.2 DHCP server: 192.168.87.254 I can ping second VM from first one. And I disabled firewalls on both machines. Any ideas? Is there any manual for this?

    Read the article

  • LINQ - IEnumerable.Join on Anonymous Result Set in VB.NET

    - by user337501
    I've long since built a way around this, but it still keeps bugging me... it doesnt help that my grasp of dynamic LINQ queries is still shakey. For the example: Parent has fields (ParentKey, ParentField) Child has fields (ChildKey, ParentKey, ChildField) Pet has fields (PetKey, ChildKey, PetField) Child has a foreign key reference to Parent on Child.ParentKey = Parent.ParentKey Pet has a foreign key reference to Child on Pet.Childkey = Child.ChildKey Simple enough eh? Lets say I have LINQ like this... Dim Q = FROM p in DataContext.Parent _ Join c In DataContext.Child On c.ParentKey = p.ParentKey Consider this a "base query" on which I will perform other filtering actions. Now I want to join the Pet table like this: Q = Q.Join(DataContext.Pet, _ Function(a) a.c.ChildKey, _ Function(p As Pet) p.ChildKey, _ Function(a, p As Pet) p.ChildKey = a.c.ChildKey) The above Join call doesnt work. I sort of understand why it doesnt work, but hopefully it'll show you how I tried to accomplish this task. After all this was done I would have appended a Select to finish the job. Any ideas on a better way to do this? I tried it with the PredicateBuilder with little success. I might not know how to use it right but it felt like it wasnt gonna handle the joining.

    Read the article

  • #Error showing up in multiple LEFT JOIN statement Access query when value should be NULL

    - by lar
    I'm trying to return an ID's last 4 years of data, if existing. The table (call it A_TABLE) looks like this: ID, Year, Val The idea behind the query is this: for each ID/Year in the table, LEFT JOIN with Year-1, Year-2, and Year-3 (to get 4 years of data) and then return Val for each year. Here's the SQL: SELECT a.ID, a.year AS [Year], a.Val AS VAL, a1.year AS [Year-1], a1.Val AS [VAL-1], a2.year AS [Year-2], a2.Val AS [VAL-2], a3.year AS [Year-3], a3.Val AS [VAL-3] FROM ( ([A_TABLE] AS a LEFT JOIN [A_TABLE] AS a1 ON (a.ID = a1.ID) AND (a.year = a1.year+1)) LEFT JOIN [A_TABLE] AS a2 ON (a.ID = a2.ID) AND (a.year = a2.year+2)) LEFT JOIN [A_TABLE] AS a3 ON (a.ID = a3.ID) AND (a.year = a3.year+3) The problem is that, for past years where there is no data (eg, Year-1), I see "#Error" in the appropriate VAL column (eg, [VAL-1]). The weird thing is, I see the expected "null" in the Year column (eg, [YEAR-1]). Some sample data: ID YEAR VAL Dave 2004 1 Dave 2006 2 Dave 2007 3 Dave 2008 5 Dave 2009 0 outputs like this: ID YEAR VAL YEAR-1 VAL-1 YEAR-2 VAL-2 YEAR-3 VAL-3 Dave 2004 1 #Error #Error #Error Dave 2006 2 #Error 2004 1 #Error Dave 2007 3 2006 2 #Error 2004 1 Dave 2008 5 2007 3 2006 2 #Error Dave 2009 0 2008 5 2007 3 2006 2 Does that make sense? Why am I getting the appropriate NULL val for the non-existent YEARs, but an #Error for the non-existent VALs? (This is Access 2000. Conditional statements like "IIf(a1.val is null, -999, a1.val)" do not seem to do anything.) EDIT: It turns out that the errors are somehow caused by the fact that A_TABLE is actually a query. When I put all the data into an actual table and run the same query, everything shows up as it should. Thanks for the help, everyone.

    Read the article

  • Join + IEqualityComparer<T> and HashCode

    - by Jesus Rodriguez
    Im writing my own LINQ reference but Im getting troubles with some of the more complicated operators implementations. There is a Join implementation that takes a IEqualityComparer Im getting just crazy. Im trying to understand it first before I write (obviously) Image this two lists: List<string> initials = new List<string> {"A", "B", "C", "D", "E"}; List<string> words = new List<string> {"Ant", "Crawl", "Pig", "Boat", "Elephant", "Arc"}; Nothing weird here. I want to join both lists by the Initial, something like: Initial=A Word=Ant Initial=A Word=Arc Initial=B Word=Boat ... I need a comparator, I wrote this: public class InitialComparator : IEqualityComparer<string> { public bool Equals(string x, string y) { return x.StartsWith(y); } public int GetHashCode(string obj) { return obj[0].GetHashCode(); } } The Join itself: var blah = initials.Join(words, initial => initial, word => word, (initial, word) => new {Initial = initial, Word = word}, new InitialComparator()); It's the first time Im using HashCodes, after a good session of debugging I see that every word go to the comparator and look at its HashCode, if another word has the same HashCode it calls equals. Since I want to compare just the initial I though that I just need the first letter Hash (Am I wrong?) The thing is that this is not working correctly. Its says that "Ant" and "Arc" are equals, Ok, its comparing every word in the same list or not, But it adds only the last word it finds, in this case Arc, ignoring Ant and Ant is equals to "A" too... If I put "Ant" and "Ant" it add both. In short, What is the way of doing something like that? I know that Im doing something wrong. Thank you.

    Read the article

  • Complex SQL query, one to many relationship

    - by Ethan
    Hey SO, I have a query such that I need to get A specific dog All comments relating to that dog The user who posted each comment All links to images of the dog the user who posted each link I've tried a several things, and can't figure out quite how to work it. Here's what I have (condensed so you don't have to wade through it all): SELECT s.dog_id, s.name, c.comment, c.date_added AS comment_date_added, u.username AS comment_username, u.user_id AS comment_user_id, l.link AS link, l.date_added AS link_date_added, u2.username AS link_username, u2.user_id AS link_user_id FROM dogs AS d LEFT JOIN comments AS c ON c.dog_id = d.dog_id LEFT JOIN users AS u ON c.user_id = u.user_id LEFT JOIN links AS l ON l.dog_id = d.dog_id LEFT JOIN users AS u2 ON l.user_id = u2.user_id WHERE d.dog_id = '1' It's sorta close to working, but it'll only return me the first comment, and the first link all as one big array with all the info i requested. The are multiple comments and links per dog, so I need it to give me all the comments and all the links. Ideally it'd return an object with dog_id, name, comments(an array of the comments), links(an array of the links) and then comments would have a bunch of comments, date_added, username, and user_id and links would have a bunch of links with link, date_added, username and user_id. It's got to work even if there are no links or comments. I learned the basics of mySQL somewhat recently, but this is pretty far over my head. Any help would be wonderful. Thanks!

    Read the article

  • creating a thread in jsp and using join has problem

    - by Suresh S
    guys the following code does not wiat for the thread t to complete and join with the main thread, also the "created object" trace is called one more time after join is called please let me know the solution <% AProc empList = new AProc(); System.out.println("** Created Object ****"); System.out.println("Condition"+(!(p.length==0) && !(status) && !(threadLive))); if (!(p.length==0) && !(status) && !(threadLive)){ java.util.Date currDate = new java.util.Date(); try { Thread t = new Thread(empList); System.out.println("Check thread life 1 "+t.isAlive()); empList.setServletRequest(request , schemaName); System.out.println("Thread Started "+t); t.start(); System.out.println("Check thread life 2 "+t.isAlive()); if(t.isAlive()) { threadLive = true; } t.join(); while (t.isAlive()) { t.join(); } System.out.println("Check thread life 3 "+t.isAlive()); System.out.println("Thread End "+t); //} } catch (Exception e) { System.out.println("Exception in thread while running Procedure "+e); status=false; threadLive=false; } status = e.getStatusProc(); }%>

    Read the article

  • sql queries slower than expected

    - by neubert
    Before I show the query here are the relevant table definitions: CREATE TABLE phpbb_posts ( topic_id mediumint(8) UNSIGNED DEFAULT '0' NOT NULL, poster_id mediumint(8) UNSIGNED DEFAULT '0' NOT NULL, KEY topic_id (topic_id), KEY poster_id (poster_id), ); CREATE TABLE phpbb_topics ( topic_id mediumint(8) UNSIGNED NOT NULL auto_increment ); Here's the query I'm trying to do: SELECT p.topic_id, p.poster_id FROM phpbb_topics AS t LEFT JOIN phpbb_posts AS p ON p.topic_id = t.topic_id AND p.poster_id <> ... WHERE p.poster_id IS NULL; Basically, the query is an attempt to find all topics where the number of times someone other than the target user has posted in is zero. In other words, the topics where the only person who has posted is the target user. Problem is that query is taking a super long time. My general assumption when it comes to SQL is that JOINs of any are super fast and can be done in no time at all assuming all relevant columns are primary or foreign keys (which in this case they are). I tried out a few other queries: SELECT COUNT(1) FROM phpbb_topics AS t JOIN phpbb_posts AS p ON p.topic_id = t.topic_id; That returns 353340 pretty quickly. I then do these: SELECT COUNT(1) FROM phpbb_topics AS t JOIN phpbb_posts AS p ON p.topic_id = t.topic_id AND p.poster_id <> 77198; SELECT COUNT(1) FROM phpbb_topics AS t JOIN phpbb_posts AS p ON p.topic_id = t.topic_id WHERE p.poster_id <> 77198; And both of those take quite a while (between 15-30 seconds). If I change the < to a = it takes no time at all. Am I making some incorrect assumptions? Maybe my DB is just foobar'd?

    Read the article

  • Java - Thread - Problem in one of the Sun's tutorial

    - by Yatendra Goel
    I was reading this Sun's tutorial on Thread. I found a block of code there which I think can be replaced by a code of fewer lines. I wonder why Sun's expert programmers followed that long way when the task can be accomplished with a code of fewer lines. I am asking this question so as to know that if I am missing something that the tutorial wants to convey. The block of code is as follows: t.start(); threadMessage("Waiting for MessageLoop thread to finish"); //loop until MessageLoop thread exits while (t.isAlive()) { threadMessage("Still waiting..."); //Wait maximum of 1 second for MessageLoop thread to //finish. t.join(1000); if (((System.currentTimeMillis() - startTime) > patience) && t.isAlive()) { threadMessage("Tired of waiting!"); t.interrupt(); //Shouldn't be long now -- wait indefinitely t.join(); } } threadMessage("Finally!"); I think that the above code can be replaced by the following: t.start(); t.join(patience); // InterruptedException is thrown by the main method so no need to handle it if(t.isAlive()) { // t's thread couldn't finish in the patience time threadMessage("Tired of waiting!"); t.interrupt(); t.join(); } threadMessage("Finally!");

    Read the article

  • Double join with habtm in ActiveRecord

    - by Daniel Huckstep
    I have a weird situation involving the need of a double inner join. I have tried the query I need, I just don't know how to make rails do it. The Data Account (has_many :sites) Site (habtm :users, belongs_to :account) User (habtm :sites) Ignore that they are habtm or whatever, I can make them habtm or has_many :through. I want to be able to do @user.accounts or @account.users Then of course I should be able to do @user.accounts < @some_other_account And then have @user.sites include all the sites from @some_other_account. I've fiddled with habtm and has_many :through but can't get it to do what I want. Basically I need to end up with a query like this (copied from phpmyadmin. Tested and works): SELECT accounts.* FROM accounts INNER JOIN sites ON sites.account_id = accounts.id INNER JOIN user_sites ON sites.id = user_sites.site_id WHERE user_sites.user_id = 2 Can I do this? Is it even a good idea to have this double join? I am assuming it would work better if users had the association with accounts to begin with, and then worry about getting @user.sites instead, but it works better for many other things if it is kept the way it is (users <- sites).

    Read the article

  • Inner or Outer left Join

    - by user1557856
    I'm having difficulty modifying a script for this situation and wondering if someone maybe able to help: I have an address table and a phone table both sharing the same column called id_number. So id_number = 2 on both tables refers to the same entity. Address and phone information used to be stored in one table (the address table) but it is now split into address and phone tables since we moved to Oracle 11g. There is a 3rd table called both_ids. This table also has an id_number column in addition to an other_ids column storing SSN and some other ids. Before the table was split into address and phone tables, I had this script: (Written in Sybase) INSERT INTO sometable_3 ( SELECT a.id_number, a.other_id, NVL(a1.addr_type_code,0) home_addr_type_code, NVL(a1.addr_status_code,0) home_addr_status_code, NVL(a1.addr_pref_ind,0) home_addr_pref_ind, NVL(a1.street1,0) home_street1, NVL(a1.street2,0) home_street2, NVL(a1.street3,0) home_street3, NVL(a1.city,0) home_city, NVL(a1.state_code,0) home_state_code, NVL(a1.zipcode,0) home_zipcode, NVL(a1.zip_suffix,0) home_zip_suffix, NVL(a1.telephone_status_code,0) home_phone_status, NVL(a1.area_code,0) home_area_code, NVL(a1.telephone_number,0) home_phone_number, NVL(a1.extension,0) home_phone_extension, NVL(a1.date_modified,'') home_date_modified FROM both_ids a, address a1 WHERE a.id_number = a1.id_number(+) AND a1.addr_type_code = 'H'); Now that we moved to Oracle 11g, the address and phone information are split. How can I modify the above script to generate the same result in Oracle 11g? Do I have to first do INNER JOIN between address and phone tables and then do a LEFT OUTER JOIN to both_ids? I tried the following and it did not work: Insert Into.. select ... FROM a1. address INNER JOIN t.Phone ON a1.id_number = t.id_number LEFT OUTER JOIN both_ids a ON a.id_number = a1.id_number WHERE a1.adrr_type_code = 'H'

    Read the article

  • The best way to return related data in a SQL statement

    - by Darvis Lombardo
    I have a question on the best method to get back to a piece of data that is in a related table on the other side of a many-to-many relationship table. My first method uses joins to get back to the data, but because there are multiple matching rows in the relationship table, I had to use a TOP 1 to get a single row result. My second method uses a subquery to get the data but this just doesn't feel right. So, my question is, which is the preferred method, or is there a better method? The script needed to create the test tables, insert data, and run the two queries is below. Thanks for your advice! Darvis -------------------------------------------------------------------------------------------- -- Create Tables -------------------------------------------------------------------------------------------- DECLARE @TableA TABLE ( [A_ID] [int] IDENTITY(1,1) NOT NULL, [Description] [varchar](50) NULL) DECLARE @TableB TABLE ( [B_ID] [int] IDENTITY(1,1) NOT NULL, [A_ID] [int] NOT NULL, [Description] [varchar](50) NOT NULL) DECLARE @TableC TABLE ( [C_ID] [int] IDENTITY(1,1) NOT NULL, [Description] [varchar](50) NOT NULL) DECLARE @TableB_C TABLE ( [B_ID] [int] NOT NULL, [C_ID] [int] NOT NULL) -------------------------------------------------------------------------------------------- -- Insert Test Data -------------------------------------------------------------------------------------------- INSERT INTO @TableA VALUES('A-One') INSERT INTO @TableA VALUES('A-Two') INSERT INTO @TableA VALUES('A-Three') INSERT INTO @TableB (A_ID, Description) VALUES(1,'B-One') INSERT INTO @TableB (A_ID, Description) VALUES(1,'B-Two') INSERT INTO @TableB (A_ID, Description) VALUES(1,'B-Three') INSERT INTO @TableB (A_ID, Description) VALUES(2,'B-Four') INSERT INTO @TableB (A_ID, Description) VALUES(2,'B-Five') INSERT INTO @TableB (A_ID, Description) VALUES(3,'B-Six') INSERT INTO @TableC VALUES('C-One') INSERT INTO @TableC VALUES('C-Two') INSERT INTO @TableC VALUES('C-Three') INSERT INTO @TableB_C (B_ID, C_ID) VALUES(1, 1) INSERT INTO @TableB_C (B_ID, C_ID) VALUES(2, 1) INSERT INTO @TableB_C (B_ID, C_ID) VALUES(3, 1) -------------------------------------------------------------------------------------------- -- Get result - method 1 -------------------------------------------------------------------------------------------- SELECT TOP 1 C.*, A.Description FROM @TableC C JOIN @TableB_C BC ON BC.C_ID = C.C_ID JOIN @TableB B ON B.B_ID = BC.B_ID JOIN @TableA A ON B.A_ID = A.A_ID WHERE C.C_ID = 1 -------------------------------------------------------------------------------------------- -- Get result - method 2 -------------------------------------------------------------------------------------------- SELECT C.*, (SELECT A.Description FROM @TableA A WHERE EXISTS (SELECT * FROM @TableB_C BC JOIN @TableB B ON B.B_ID = BC.B_ID WHERE BC.C_ID = C.C_ID AND B.A_ID = A.A_ID)) FROM @TableC C WHERE C.C_ID = 1

    Read the article

  • Windows setevent processsing

    - by Waldorf
    I wonder how setevent is handled internally within Windows. I have the following situation Std::thread thread loop which executes while std::atomic == true Inside the loop is a waitforsingleObject which sleeps infinite in alertable state. A function stopThread() which does the following: - Clears the atomic bool - Calls Setevent on the event object - Calls thread.join This often hangs, I get the impression that setevent has still some work to do in the current thread, while join blocks the current thread. If I add an additional Boolean in the thread which is set after waitforsinlgleObject and I wait for this to be set before calling join() Everything seems to work ok. Code (error checking omitted here) Init code/declarations: HANDLE m_WakeupThreadEvent; std::atomic<bool> m_ReceiverEnabled; m_WakeupThreadEvent = CreateEvent(NULL, false, false, "RxThreadWakeupEvent" ); Thread code: while(m_ReceiverEnabled) { DWORD rslt = WaitForSingleObjectEx(m_WakeupThreadEvent, INFINITE, true); // Here some checking for rslt; } function code: m_ReceiverEnabled = true; SetEvent( m_WakeupThreadEvent ) m_Thread.join() Is there some explanation for this behavior ? I could not find any details about the operation of setEvent()

    Read the article

  • TSQL Conditionally Select Specific Value

    - by Dzejms
    This is a follow-up to #1644748 where I successfully answered my own question, but Quassnoi helped me to realize that it was the wrong question. He gave me a solution that worked for my sample data, but I couldn't plug it back into the parent stored procedure because I fail at SQL 2005 syntax. So here is an attempt to paint the broader picture and ask what I actually need. This is part of a stored procedure that returns a list of items in a bug tracking application I've inherited. There are are over 100 fields and 26 joins so I'm pulling out only the mostly relevant bits. SELECT tickets.ticketid, tickets.tickettype, tickets_tickettype_lu.tickettypedesc, tickets.stage, tickets.position, tickets.sponsor, tickets.dev, tickets.qa, DATEDIFF(DAY, ticket_history_assignment.savedate, GETDATE()) as 'daysinqueue' FROM dbo.tickets WITH (NOLOCK) LEFT OUTER JOIN dbo.tickets_tickettype_lu WITH (NOLOCK) ON tickets.tickettype = tickets_tickettype_lu.tickettypeid LEFT OUTER JOIN dbo.tickets_history_assignment WITH (NOLOCK) ON tickets_history_assignment.ticketid = tickets.ticketid AND tickets_history_assignment.historyid = ( SELECT MAX(historyid) FROM dbo.tickets_history_assignment WITH (NOLOCK) WHERE tickets_history_assignment.ticketid = tickets.ticketid GROUP BY tickets_history_assignment.ticketid ) WHERE tickets.sponsor = @sponsor The area of interest is the daysinqueue subquery mess. The tickets_history_assignment table looks roughly as follows declare @tickets_history_assignment table ( historyid int, ticketid int, sponsor int, dev int, qa int, savedate datetime ) insert into @tickets_history_assignment values (1521402, 92774,20,14, 20, '2009-10-27 09:17:59.527') insert into @tickets_history_assignment values (1521399, 92774,20,14, 42, '2009-08-31 12:07:52.917') insert into @tickets_history_assignment values (1521311, 92774,100,14, 42, '2008-12-08 16:15:49.887') insert into @tickets_history_assignment values (1521336, 92774,100,14, 42, '2009-01-16 14:27:43.577') Whenever a ticket is saved, the current values for sponsor, dev and qa are stored in the tickets_history_assignment table with the ticketid and a timestamp. So it is possible for someone to change the value for qa, but leave sponsor alone. What I want to know, based on all of these conditions, is the historyid of the record in the tickets_history_assignment table where the sponsor value was last changed so that I can calculate the value for daysinqueue. If a record is inserted into the history table, and only the qa value has changed, I don't want that record. So simply relying on MAX(historyid) won't work for me. Quassnoi came up with the following which seemed to work with my sample data, but I can't plug it into the larger query, SQL Manager bitches about the WITH statement. ;WITH rows AS ( SELECT *, ROW_NUMBER() OVER (PARTITION BY ticketid ORDER BY savedate DESC) AS rn FROM @Table ) SELECT rl.sponsor, ro.savedate FROM rows rl CROSS APPLY ( SELECT TOP 1 rc.savedate FROM rows rc JOIN rows rn ON rn.ticketid = rc.ticketid AND rn.rn = rc.rn + 1 AND rn.sponsor <> rc.sponsor WHERE rc.ticketid = rl.ticketid ORDER BY rc.rn ) ro WHERE rl.rn = 1 I played with it yesterday afternoon and got nowhere because I don't fundamentally understand what is going on here and how it should fit into the larger context. So, any takers? UPDATE Ok, here's the whole thing. I've been switching some of the table and column names in an attempt to simplify things so here's the full unedited mess. snip - old bad code Here are the errors: Msg 102, Level 15, State 1, Procedure usp_GetProjectRecordsByAssignment, Line 159 Incorrect syntax near ';'. Msg 102, Level 15, State 1, Procedure usp_GetProjectRecordsByAssignment, Line 179 Incorrect syntax near ')'. Line numbers are of course not correct but refer to ;WITH rows AS And the ')' char after the WHERE rl.rn = 1 ) Respectively Is there a tag for extra super long question? UPDATE #2 Here is the finished query for anyone who may need this: CREATE PROCEDURE [dbo].[usp_GetProjectRecordsByAssignment] ( @assigned numeric(18,0), @assignedtype numeric(18,0) ) AS SET NOCOUNT ON WITH rows AS ( SELECT *, ROW_NUMBER() OVER (PARTITION BY recordid ORDER BY savedate DESC) AS rn FROM projects_history_assignment ) SELECT projects_records.recordid, projects_records.recordtype, projects_recordtype_lu.recordtypedesc, projects_records.stage, projects_stage_lu.stagedesc, projects_records.position, projects_position_lu.positiondesc, CASE projects_records.clientrequested WHEN '1' THEN 'Yes' WHEN '0' THEN 'No' END AS clientrequested, projects_records.reportingmethod, projects_reportingmethod_lu.reportingmethoddesc, projects_records.clientaccess, projects_clientaccess_lu.clientaccessdesc, projects_records.clientnumber, projects_records.project, projects_lu.projectdesc, projects_records.version, projects_version_lu.versiondesc, projects_records.projectedversion, projects_version_lu_projected.versiondesc AS projectedversiondesc, projects_records.sitetype, projects_sitetype_lu.sitetypedesc, projects_records.title, projects_records.module, projects_module_lu.moduledesc, projects_records.component, projects_component_lu.componentdesc, projects_records.loginusername, projects_records.loginpassword, projects_records.assistedusername, projects_records.browsername, projects_browsername_lu.browsernamedesc, projects_records.browserversion, projects_records.osname, projects_osname_lu.osnamedesc, projects_records.osversion, projects_records.errortype, projects_errortype_lu.errortypedesc, projects_records.gsipriority, projects_gsipriority_lu.gsiprioritydesc, projects_records.clientpriority, projects_clientpriority_lu.clientprioritydesc, projects_records.scheduledstartdate, projects_records.scheduledcompletiondate, projects_records.projectedhours, projects_records.actualstartdate, projects_records.actualcompletiondate, projects_records.actualhours, CASE projects_records.billclient WHEN '1' THEN 'Yes' WHEN '0' THEN 'No' END AS billclient, projects_records.billamount, projects_records.status, projects_status_lu.statusdesc, CASE CAST(projects_records.assigned AS VARCHAR(5)) WHEN '0' THEN 'N/A' WHEN '10000' THEN 'Unassigned' WHEN '20000' THEN 'Client' WHEN '30000' THEN 'Tech Support' WHEN '40000' THEN 'LMI Tech Support' WHEN '50000' THEN 'Upload' WHEN '60000' THEN 'Spider' WHEN '70000' THEN 'DB Admin' ELSE rtrim(users_assigned.nickname) + ' ' + rtrim(users_assigned.lastname) END AS assigned, CASE CAST(projects_records.assigneddev AS VARCHAR(5)) WHEN '0' THEN 'N/A' WHEN '10000' THEN 'Unassigned' ELSE rtrim(users_assigneddev.nickname) + ' ' + rtrim(users_assigneddev.lastname) END AS assigneddev, CASE CAST(projects_records.assignedqa AS VARCHAR(5)) WHEN '0' THEN 'N/A' WHEN '10000' THEN 'Unassigned' ELSE rtrim(users_assignedqa.nickname) + ' ' + rtrim(users_assignedqa.lastname) END AS assignedqa, CASE CAST(projects_records.assignedsponsor AS VARCHAR(5)) WHEN '0' THEN 'N/A' WHEN '10000' THEN 'Unassigned' ELSE rtrim(users_assignedsponsor.nickname) + ' ' + rtrim(users_assignedsponsor.lastname) END AS assignedsponsor, projects_records.clientcreated, CASE projects_records.clientcreated WHEN '1' THEN 'Yes' WHEN '0' THEN 'No' END AS clientcreateddesc, CASE projects_records.clientcreated WHEN '1' THEN rtrim(clientusers_createuser.firstname) + ' ' + rtrim(clientusers_createuser.lastname) + ' (Client)' ELSE rtrim(users_createuser.nickname) + ' ' + rtrim(users_createuser.lastname) END AS createuser, projects_records.createdate, projects_records.savedate, projects_resolution.sitesaffected, projects_sitesaffected_lu.sitesaffecteddesc, DATEDIFF(DAY, projects_history_assignment.savedate, GETDATE()) as 'daysinqueue', projects_records.iOnHitList, projects_records.changetype FROM dbo.projects_records WITH (NOLOCK) LEFT OUTER JOIN dbo.projects_recordtype_lu WITH (NOLOCK) ON projects_records.recordtype = projects_recordtype_lu.recordtypeid LEFT OUTER JOIN dbo.projects_stage_lu WITH (NOLOCK) ON projects_records.stage = projects_stage_lu.stageid LEFT OUTER JOIN dbo.projects_position_lu WITH (NOLOCK) ON projects_records.position = projects_position_lu.positionid LEFT OUTER JOIN dbo.projects_reportingmethod_lu WITH (NOLOCK) ON projects_records.reportingmethod = projects_reportingmethod_lu.reportingmethodid LEFT OUTER JOIN dbo.projects_lu WITH (NOLOCK) ON projects_records.project = projects_lu.projectid LEFT OUTER JOIN dbo.projects_version_lu WITH (NOLOCK) ON projects_records.version = projects_version_lu.versionid LEFT OUTER JOIN dbo.projects_version_lu projects_version_lu_projected WITH (NOLOCK) ON projects_records.projectedversion = projects_version_lu_projected.versionid LEFT OUTER JOIN dbo.projects_sitetype_lu WITH (NOLOCK) ON projects_records.sitetype = projects_sitetype_lu.sitetypeid LEFT OUTER JOIN dbo.projects_module_lu WITH (NOLOCK) ON projects_records.module = projects_module_lu.moduleid LEFT OUTER JOIN dbo.projects_component_lu WITH (NOLOCK) ON projects_records.component = projects_component_lu.componentid LEFT OUTER JOIN dbo.projects_browsername_lu WITH (NOLOCK) ON projects_records.browsername = projects_browsername_lu.browsernameid LEFT OUTER JOIN dbo.projects_osname_lu WITH (NOLOCK) ON projects_records.osname = projects_osname_lu.osnameid LEFT OUTER JOIN dbo.projects_errortype_lu WITH (NOLOCK) ON projects_records.errortype = projects_errortype_lu.errortypeid LEFT OUTER JOIN dbo.projects_resolution WITH (NOLOCK) ON projects_records.recordid = projects_resolution.recordid LEFT OUTER JOIN dbo.projects_sitesaffected_lu WITH (NOLOCK) ON projects_resolution.sitesaffected = projects_sitesaffected_lu.sitesaffectedid LEFT OUTER JOIN dbo.projects_gsipriority_lu WITH (NOLOCK) ON projects_records.gsipriority = projects_gsipriority_lu.gsipriorityid LEFT OUTER JOIN dbo.projects_clientpriority_lu WITH (NOLOCK) ON projects_records.clientpriority = projects_clientpriority_lu.clientpriorityid LEFT OUTER JOIN dbo.projects_status_lu WITH (NOLOCK) ON projects_records.status = projects_status_lu.statusid LEFT OUTER JOIN dbo.projects_clientaccess_lu WITH (NOLOCK) ON projects_records.clientaccess = projects_clientaccess_lu.clientaccessid LEFT OUTER JOIN dbo.users users_assigned WITH (NOLOCK) ON projects_records.assigned = users_assigned.userid LEFT OUTER JOIN dbo.users users_assigneddev WITH (NOLOCK) ON projects_records.assigneddev = users_assigneddev.userid LEFT OUTER JOIN dbo.users users_assignedqa WITH (NOLOCK) ON projects_records.assignedqa = users_assignedqa.userid LEFT OUTER JOIN dbo.users users_assignedsponsor WITH (NOLOCK) ON projects_records.assignedsponsor = users_assignedsponsor.userid LEFT OUTER JOIN dbo.users users_createuser WITH (NOLOCK) ON projects_records.createuser = users_createuser.userid LEFT OUTER JOIN dbo.clientusers clientusers_createuser WITH (NOLOCK) ON projects_records.createuser = clientusers_createuser.userid LEFT OUTER JOIN dbo.projects_history_assignment WITH (NOLOCK) ON projects_history_assignment.recordid = projects_records.recordid AND projects_history_assignment.historyid = ( SELECT ro.historyid FROM rows rl CROSS APPLY ( SELECT TOP 1 rc.historyid FROM rows rc JOIN rows rn ON rn.recordid = rc.recordid AND rn.rn = rc.rn + 1 AND rn.assigned <> rc.assigned WHERE rc.recordid = rl.recordid ORDER BY rc.rn ) ro WHERE rl.rn = 1 AND rl.recordid = projects_records.recordid ) WHERE (@assignedtype='0' and projects_records.assigned = @assigned) OR (@assignedtype='1' and projects_records.assigneddev = @assigned) OR (@assignedtype='2' and projects_records.assignedqa = @assigned) OR (@assignedtype='3' and projects_records.assignedsponsor = @assigned) OR (@assignedtype='4' and projects_records.createuser = @assigned)

    Read the article

  • How to join dynamic sql statement in variable with normal statement

    - by Oliver
    I have a quite complicated query which will by built up dynamically and is saved in a variable. As second part i have another normal query and i'd like to make an inner join between these both. To make it a little more easier here is a little example to illustrate my problem. For this little example i used the AdventureWorks database. Some query built up dynamically (Yes, i know here is nothing dynamic here, cause it's just an example.) DECLARE @query AS varchar(max) ; set @query = ' select HumanResources.Employee.EmployeeID ,HumanResources.Employee.LoginID ,HumanResources.Employee.Title ,HumanResources.EmployeeAddress.AddressID from HumanResources.Employee inner join HumanResources.EmployeeAddress on HumanResources.Employee.EmployeeID = HumanResources.EmployeeAddress.EmployeeID ;'; EXEC (@query); The normal query i have select Person.Address.AddressID ,Person.Address.City from Person.Address Maybe what i'd like to have but doesn't work select @query.* ,Addresses.City from @query as Employees inner join ( select Person.Address.AddressID ,Person.Address.City from Person.Address ) as Addresses on Employees.AddressID = Addresses.AddressID

    Read the article

  • In cakePHP, how to retrieve joined result from multiple tables

    - by Manish Sharma
    Hi, can anyone tell me, how to retrieve joined result from multiple tables in cakePHP ( using cakePHP mvc architecture). For example, I have three tables to join (tbl_topics, tbl_items, tbl_votes. Their relationship is defined as following: a topic can have many items and an item can have many votes. Now I want to retrieve a list of topics with the count of all votes on all items for each topic. The SQL query for this is written below: SELECT Topic.*, count(Vote.id) voteCount FROM tbl_topics AS Topic LEFT OUTER JOIN tbl_items AS Item ON (Topic.id = Item.topic_id) LEFT OUTER JOIN tbl_votes AS Vote ON (Item.id = Vote.item_id); My problem is I can do it easily using $this-><Model Name>->query function, but this requires sql code to be written in the controller which I don't want. I'm trying to find out any other way to do this (like find()).

    Read the article

< Previous Page | 18 19 20 21 22 23 24 25 26 27 28 29  | Next Page >