Search Results

Search found 21742 results on 870 pages for 'unique values'.

Page 15/870 | < Previous Page | 11 12 13 14 15 16 17 18 19 20 21 22  | Next Page >

  • C#/.NET Little Pitfalls: The Dangers of Casting Boxed Values

    - by James Michael Hare
    Starting a new series to parallel the Little Wonders series.  In this series, I will examine some of the small pitfalls that can occasionally trip up developers. Introduction: Of Casts and Conversions What happens when we try to assign from an int and a double and vice-versa? 1: double pi = 3.14; 2: int theAnswer = 42; 3:  4: // implicit widening conversion, compiles! 5: double doubleAnswer = theAnswer; 6:  7: // implicit narrowing conversion, compiler error! 8: int intPi = pi; As you can see from the comments above, a conversion from a value type where there is no potential data loss is can be done with an implicit conversion.  However, when converting from one value type to another may result in a loss of data, you must make the conversion explicit so the compiler knows you accept this risk.  That is why the conversion from double to int will not compile with an implicit conversion, we can make the conversion explicit by adding a cast: 1: // explicit narrowing conversion using a cast, compiler 2: // succeeds, but results may have data loss: 3: int intPi = (int)pi; So for value types, the conversions (implicit and explicit) both convert the original value to a new value of the given type.  With widening and narrowing references, however, this is not the case.  Converting reference types is a bit different from converting value types.  First of all when you perform a widening or narrowing you don’t really convert the instance of the object, you just convert the reference itself to the wider or narrower reference type, but both the original and new reference type both refer back to the same object. Secondly, widening and narrowing for reference types refers the going down and up the class hierarchy instead of referring to precision as in value types.  That is, a narrowing conversion for a reference type means you are going down the class hierarchy (for example from Shape to Square) whereas a widening conversion means you are going up the class hierarchy (from Square to Shape).  1: var square = new Square(); 2:  3: // implicitly convers because all squares are shapes 4: // (that is, all subclasses can be referenced by a superclass reference) 5: Shape myShape = square; 6:  7: // implicit conversion not possible, not all shapes are squares! 8: // (that is, not all superclasses can be referenced by a subclass reference) 9: Square mySquare = (Square) myShape; So we had to cast the Shape back to Square because at that point the compiler has no way of knowing until runtime whether the Shape in question is truly a Square.  But, because the compiler knows that it’s possible for a Shape to be a Square, it will compile.  However, if the object referenced by myShape is not truly a Square at runtime, you will get an invalid cast exception. Of course, there are other forms of conversions as well such as user-specified conversions and helper class conversions which are beyond the scope of this post.  The main thing we want to focus on is this seemingly innocuous casting method of widening and narrowing conversions that we come to depend on every day and, in some cases, can bite us if we don’t fully understand what is going on!  The Pitfall: Conversions on Boxed Value Types Can Fail What if you saw the following code and – knowing nothing else – you were asked if it was legal or not, what would you think: 1: // assuming x is defined above this and this 2: // assignment is syntactically legal. 3: x = 3.14; 4:  5: // convert 3.14 to int. 6: int truncated = (int)x; You may think that since x is obviously a double (can’t be a float) because 3.14 is a double literal, but this is inaccurate.  Our x could also be dynamic and this would work as well, or there could be user-defined conversions in play.  But there is another, even simpler option that can often bite us: what if x is object? 1: object x; 2:  3: x = 3.14; 4:  5: int truncated = (int) x; On the surface, this seems fine.  We have a double and we place it into an object which can be done implicitly through boxing (no cast) because all types inherit from object.  Then we cast it to int.  This theoretically should be possible because we know we can explicitly convert a double to an int through a conversion process which involves truncation. But here’s the pitfall: when casting an object to another type, we are casting a reference type, not a value type!  This means that it will attempt to see at runtime if the value boxed and referred to by x is of type int or derived from type int.  Since it obviously isn’t (it’s a double after all) we get an invalid cast exception! Now, you may say this looks awfully contrived, but in truth we can run into this a lot if we’re not careful.  Consider using an IDataReader to read from a database, and then attempting to select a result row of a particular column type: 1: using (var connection = new SqlConnection("some connection string")) 2: using (var command = new SqlCommand("select * from employee", connection)) 3: using (var reader = command.ExecuteReader()) 4: { 5: while (reader.Read()) 6: { 7: // if the salary is not an int32 in the SQL database, this is an error! 8: // doesn't matter if short, long, double, float, reader [] returns object! 9: total += (int) reader["annual_salary"]; 10: } 11: } Notice that since the reader indexer returns object, if we attempt to convert using a cast to a type, we have to make darn sure we use the true, actual type or this will fail!  If the SQL database column is a double, float, short, etc this will fail at runtime with an invalid cast exception because it attempts to convert the object reference! So, how do you get around this?  There are two ways, you could first cast the object to its actual type (double), and then do a narrowing cast to on the value to int.  Or you could use a helper class like Convert which analyzes the actual run-time type and will perform a conversion as long as the type implements IConvertible. 1: object x; 2:  3: x = 3.14; 4:  5: // if you want to cast, must cast out of object to double, then 6: // cast convert. 7: int truncated = (int)(double) x; 8:  9: // or you can call a helper class like Convert which examines runtime 10: // type of the value being converted 11: int anotherTruncated = Convert.ToInt32(x); Summary You should always be careful when performing a conversion cast from values boxed in object that you are actually casting to the true type (or a sub-type). Since casting from object is a widening of the reference, be careful that you either know the exact, explicit type you expect to be held in the object, or instead avoid the cast and use a helper class to perform a safe conversion to the type you desire. Technorati Tags: C#,.NET,Pitfalls,Little Pitfalls,BlackRabbitCoder

    Read the article

  • On StringComparison Values

    - by Jesse
    When you use the .NET Framework’s String.Equals and String.Compare methods do you use an overloStringComparison enumeration value? If not, you should be because the value provided for that StringComparison argument can have a big impact on the results of your string comparison. The StringComparison enumeration defines values that fall into three different major categories: Culture-sensitive comparison using a specific culture, defaulted to the Thread.CurrentThread.CurrentCulture value (StringComparison.CurrentCulture and StringComparison.CurrentCutlureIgnoreCase) Invariant culture comparison (StringComparison.InvariantCulture and StringComparison.InvariantCultureIgnoreCase) Ordinal (byte-by-byte) comparison of  (StringComparison.Ordinal and StringComparison.OrdinalIgnoreCase) There is a lot of great material available that detail the technical ins and outs of these different string comparison approaches. If you’re at all interested in the topic these two MSDN articles are worth a read: Best Practices For Using Strings in the .NET Framework: http://msdn.microsoft.com/en-us/library/dd465121.aspx How To Compare Strings: http://msdn.microsoft.com/en-us/library/cc165449.aspx Those articles cover the technical details of string comparison well enough that I’m not going to reiterate them here other than to say that the upshot is that you typically want to use the culture-sensitive comparison whenever you’re comparing strings that were entered by or will be displayed to users and the ordinal comparison in nearly all other cases. So where does that leave the invariant culture comparisons? The “Best Practices For Using Strings in the .NET Framework” article has the following to say: “On balance, the invariant culture has very few properties that make it useful for comparison. It does comparison in a linguistically relevant manner, which prevents it from guaranteeing full symbolic equivalence, but it is not the choice for display in any culture. One of the few reasons to use StringComparison.InvariantCulture for comparison is to persist ordered data for a cross-culturally identical display. For example, if a large data file that contains a list of sorted identifiers for display accompanies an application, adding to this list would require an insertion with invariant-style sorting.” I don’t know about you, but I feel like that paragraph is a bit lacking. Are there really any “real world” reasons to use the invariant culture comparison? I think the answer to this question is, “yes”, but in order to understand why we should first think about what the invariant culture comparison really does. The invariant culture comparison is really just a culture-sensitive comparison using a special invariant culture (Michael Kaplan has a great post on the history of the invariant culture on his blog: http://blogs.msdn.com/b/michkap/archive/2004/12/29/344136.aspx). This means that the invariant culture comparison will apply the linguistic customs defined by the invariant culture which are guaranteed not to differ between different machines or execution contexts. This sort of consistently does prove useful if you needed to maintain a list of strings that are sorted in a meaningful and consistent way regardless of the user viewing them or the machine on which they are being viewed. Example: Prototype Names Let’s say that you work for a large multi-national toy company with branch offices in 10 different countries. Each year the company would work on 15-25 new toy prototypes each of which is assigned a “code name” while it is under development. Coming up with fun new code names is a big part of the company culture that everyone really enjoys, so to be fair the CEO of the company spent a lot of time coming up with a prototype naming scheme that would be fun for everyone to participate in, fair to all of the different branch locations, and accessible to all members of the organization regardless of the country they were from and the language that they spoke. Each new prototype will get a code name that begins with a letter following the previously created name using the alphabetical order of the Latin/Roman alphabet. Each new year prototype names would start back at “A”. The country that leads the prototype development effort gets to choose the name in their native language. (An appropriate Romanization system will be used for countries where the primary language is not written in the Latin/Roman alphabet. For example, the Pinyin system could be used for Chinese). To avoid repeating names, a list of all current and past prototype names will be maintained on each branch location’s company intranet site. Assuming that maintaining a single pre-sorted list is not feasible among all of the highly distributed intranet implementations, what string comparison method would you use to sort each year’s list of prototype names so that the list is both meaningful and consistent regardless of the country within which the list is being viewed? Sorting the list with a culture-sensitive comparison using the default configured culture on each country’s intranet server the list would probably work most of the time, but subtle differences between cultures could mean that two different people would see a list that was sorted slightly differently. The CEO wants the prototype names to be a unifying aspect of company culture and is adamant that everyone see the the same list sorted in the same order and there’s no way to guarantee a consistent sort across different cultures using the culture-sensitive string comparison rules. The culture-sensitive sort would produce a meaningful list for the specific user viewing it, but it wouldn’t always be consistent between different users. Sorting with the ordinal comparison would certainly be consistent regardless of the user viewing it, but would it be meaningful? Let’s say that the current year’s prototype name list looks like this: Antílope (Spanish) Babouin (French) Cahoun (Czech) Diamond (English) Flosse (German) If you were to sort this list using ordinal rules you’d end up with: Antílope Babouin Diamond Flosse Cahoun This sort is no good because the entry for “C” appears the bottom of the list after “F”. This is because the Czech entry for the letter “C” makes use of a diacritic (accent mark). The ordinal string comparison does a byte-by-byte comparison of the code points that make up each character in the string and the code point for the “C” with the diacritic mark is higher than any letter without a diacritic mark, which pushes that entry to the bottom of the sorted list. The CEO wants each country to be able to create prototype names in their native language, which means we need to allow for names that might begin with letters that have diacritics, so ordinal sorting kills the meaningfulness of the list. As it turns out, this situation is actually well-suited for the invariant culture comparison. The invariant culture accounts for linguistically relevant factors like the use of diacritics but will provide a consistent sort across all machines that perform the sort. Now that we’ve walked through this example, the following line from the “Best Practices For Using Strings in the .NET Framework” makes a lot more sense: One of the few reasons to use StringComparison.InvariantCulture for comparison is to persist ordered data for a cross-culturally identical display That line describes the prototype name example perfectly: we need a way to persist ordered data for a cross-culturally identical display. While this example is 100% made-up, I think it illustrates that there are indeed real-world situations where the invariant culture comparison is useful.

    Read the article

  • Unique Keys not recognized by Entity Framework

    - by David Pfeffer
    I have two tables, Reports and Visualizations. Reports has a field, VisualizationID, which points to Visualization's field of the same name via a foreign key. It also has a unique key declared on the field. VisualizationID is not nullable. This means the relationship has to be 0..1 to 1, because every Reports record must have a unique, not null Visualizations record associated with it. The Entity Framework doesn't see it this way. I'm getting the following error: Error 113: Multiplicity is not valid in Role 'Report' in relationship 'FK_Reports_Visualizations'. Because the Dependent Role properties are not the key properties, the upper bound of the multiplicity of the Dependent Role must be *. What's the problem here? How can I make the EF recognize the proper relationship multiplicity?

    Read the article

  • Django: UserProfile with Unique Foreign Key in Django Admin

    - by lazerscience
    Hi, I have extended Django's User Model using a custom user profile called UserExtension. It is related to User through a unique ForeignKey Relationship, which enables me to edit it in the admin in an inline form! I'm using a signal to create a new profile for every new user: def create_user_profile(sender, instance, created, **kwargs): if created: try: profile, created = UserExtension.objects.get_or_create(user=instance) except: pass post_save.connect(create_user_profile, sender=User) (as described here for example: http://stackoverflow.com/questions/44109/extending-the-user-model-with-custom-fields-in-django) The problem is, that, if I create a new user through the admin, I get an IntegritiyError on saving "column user_id is not unique". It doesnt seem that the signal is called twice, but i guess the admin is trying to save the profile AFTERWARDS? But I need the creation through signal if I create a new user in other parts of the system!

    Read the article

  • Unique ID for MS Word 2007 paragraph

    - by Ganish
    I am writing large MS Word 2007 documents, which are often being changed. I have to number paragraphs with stationary unique numbers, that will not change while changing the documents. The numbers should be unique, and will not change even if previous numbers are deleted. The order of the list is not mandatory, and addition of a new number before existing numbers is possible (for instance: the sequence 1, 4, 3 means that paragraphs 1-3 were written, then #2 was deleted, then #5 was added. #3 was not affected by the later editing) The mechanism should be internal to the document, as I am working on line and off line. The numbers are allocated to every document individually. Since I don't know to program under MS Word, I'd appreciate getting a complete solution.

    Read the article

  • ASP.NET MVC Route Default values

    - by Sadegh
    hi, i defined two routes in global.asax like below context.MapRoute("HomeRedirect", "", new { controller = "Home", action = "redirect" }); context.MapRoute("UrlResolver", "{culture}/some", new { culture = "en-gb", controller = "someController", action = "someAction" }, new { culture = new CultureRouteConstraint() }); according to above definition, when user request mysite.com/ redirect action of HomeController should be called and in that: public class HomeController : Controller { public ActionResult Redirect() { return RedirectToRoute("UrlResolver"); } } i want to redirect user to second defined route on above, so also i specified default values for that and some Constraint for each of those. but when RedirectToRoute("UrlResolver") turns, no default values passed to routeConstraints on second route and No route in the route table matches the supplied values shows. update my CultureRouteConstraint: public class CultureRouteConstraint : IRouteConstraint { bool IRouteConstraint.Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection) { try { var parameter = values[parameterName] as string; return (someCondition(parameter)); } catch { return false; } } } now values parameter haven't culture key/value, but route parameter have that.

    Read the article

  • JPA 2.0 EclipseLink Check for unique

    - by Parhs
    Hello... I have a collumn as unique=true.. in Exam class.... I found that because transactions are commited automaticaly so to force the commit i use em.commit() However i would like to know how to check if it is unique.Running a query isnt a solution because it may be an instert after checking because of the concurency.... Which is the best way to check for uniqness? List<Exam_Normal> exam_normals = exam.getExam_Normal(); exam.setExam_Normal(null); try { em.persist(exam); em.flush(); Long i = 0L; if (exam_normals != null) { for (Exam_Normal e_n : exam_normals) { i++; e_n.setItem(i); e_n.setId(exam); em.persist(e_n); } } } catch (Exception e) { System.out.print("sfalma--"); } } d

    Read the article

  • Unique ID for WORD2007 paragraph

    - by Ganish
    Hello, I am writing large WORD2007 socuments, which are often being changed. I ahve to number paragraphs with stationary unique unmbers, that will not change while changing the documents. The numbers should be unique, and will not change even if previous numbers are deleted. The order of the list is not mandatory, and addition of a new number before existing numbers is possible (for instance: the sequence 1, 4, 3 means that paragraphs 1-3 were written, then #2 was deleted, then #5 was added. #3 was not affected by the later editing) The mechanism should be internal to the document, as I am working on line and off line. The numbers are allocated to every document indovidually. Since I don't know to program under WORD, I'd appreciate getting complete solution. REgards Ganish

    Read the article

  • DDD - Validation of unique constraint

    - by W3Max
    In DDD you should never let your entities enter an invalid state. That being said, how do you handle the validation of a unique constraint? The creation of an entity is not a real problem. But let say you have an entity that must have a unique name and there is a thousand instances of this entity type - they are not in memory but stored in a database. Now let say you want to rename an instance. You can't just use a setter... the object could enter an invalid state - you have to validate against the database. How do you handle this scenario in a web environment?

    Read the article

  • MySQL unique clustered constraint not constraining as expected

    - by igor
    I'm creating a table with: CREATE TABLE movies ( id INT AUTO_INCREMENT PRIMARY KEY, name CHAR(255) NOT NULL, year INT NOT NULL, inyear CHAR(10), CONSTRAINT UNIQUE CLUSTERED (name, year, inyear) ); (this is jdbc SQL) Which creates a MySQL table with a clustered index, "index kind" is "unique", and spans the three clustered columns: full size However, once I dump my data (without exceptions thrown), I see that the uniqueness constraint has failed: SELECT * FROM movies WHERE name = 'Flawless' AND year = 2007 AND inyear IS NULL; gives: id, name, year, inyear 162169, 'Flawless', 2007, NULL 162170, 'Flawless', 2007, NULL Does anyone know what I'm doing wrong here?

    Read the article

  • Unique ID Defined by Most-Derived Class accessible through Base Class

    - by Narfanator
    Okay, so, the idea is that I have a map of "components", which inherit from componentBase, and are keyed on an ID unique to the most-derived*. Only, I can't think of a good way to get this to work. I tried it with the constructor, but that doesn't work (Maybe I did it wrong). The problem with any virtual, etc, inheritance tricks are that the user has to impliment them at the bottom, which can be forgotten and makes it less... clean. *Right phrase? If - is inheritance; foo is most-derived: foo-foo1-foo2-componentBase Here's some code showing the problem, and why CRTP can't cut it: (No, it's not legit code, but I'm trying to get my thoughts down) #include<map> class componentBase { public: virtual static char idFunction() = 0; }; template <class T> class component : public virtual componentBase { public: static char idFunction(){ return reinterpret_cast<char>(&idFunction); } }; class intermediateDerivations1 : public virtual component<intermediateDerivations1> { }; class intermediateDerivations2 : public virtual component<intermediateDerivations2> { }; class derived1 : public intermediateDerivations1 { }; class derived2 : public intermediateDerivations1 { }; //How the unique ID gets used (more or less) std::map<char, componentBase*> TheMap; template<class T> void addToMap(componentBase * c) { TheMap[T::idFunction()] = c; } template<class T> T * getFromMap() { return TheMap[T::idFunction()]; } int main() { //In each case, the key needs to be different. //For these, the CRTP should do it: getFromMap<intermediateDerivations1>(); getFromMap<intermediateDerivations2>(); //But not for these. getFromMap<derived1>(); getFromMap<derived2>(); return 0; } More or less, I need something that is always there, no matter what the user does, and has a sortable value that's unique to the most-derived class. Also, I realize this isn't the best-asked question, I'm actually having some unexpected difficultly wrapping my head around it in words, so ask questions if/when you need clarification.

    Read the article

  • Averaging initial values for rolling series

    - by Dave Jarvis
    Question Given a maximum sliding window size of 40 (i.e., the set of numbers in the list cannot exceed 40), what is the calculation to ensure a smooth averaging transition as the set size grows from 1 to 40? Problem Description Creating a trend line for a set of data has skewed initial values. The complete set of values is unknown at runtime: they are provided one at a time. It seems like a reverse-weighted average is required so that the initial values are averaged differently. In the image below the leftmost data for the trend line are incorrectly averaged. Current Solution Created a new type of ArrayList subclass that calculates the appropriate values and ensures its size never goes beyond the bounds of the sliding window: /** * A list of Double values that has a maximum capacity enforced by a sliding * window. Can calculate the average of its values. */ public class AveragingList extends ArrayList<Double> { private float slidingWindowSize = 0.0f; /** * The initial capacity is used for the sliding window size. * @param slidingWindowSize */ public AveragingList( int slidingWindowSize ) { super( slidingWindowSize ); setSlidingWindowSize( ( float )slidingWindowSize ); } public boolean add( Double d ) { boolean result = super.add( d ); // Prevent the list from exceeding the maximum sliding window size. // if( size() > getSlidingWindowSize() ) { remove( 0 ); } return result; } /** * Calculate the average. * * @return The average of the values stored in this list. */ public double average() { double result = 0.0; int size = size(); for( Double d: this ) { result += d.doubleValue(); } return (double)result / (double)size; } /** * Changes the maximum number of numbers stored in this list. * * @param slidingWindowSize New maximum number of values to remember. */ public void setSlidingWindowSize( float slidingWindowSize ) { this.slidingWindowSize = slidingWindowSize; } /** * Returns the number used to determine the maximum values this list can * store before it removes the first entry upon adding another value. * @return The maximum number of numbers stored in this list. */ public float getSlidingWindowSize() { return slidingWindowSize; } } Resulting Image Example Input The data comes into the function one value at a time. For example, data points (Data) and calculated averages (Avg) typically look as follows: Data: 17.0 Avg : 17.0 Data: 17.0 Avg : 17.0 Data: 5.0 Avg : 13.0 Data: 5.0 Avg : 11.0  Related Sites The following pages describe moving averages, but typically when all (or sufficient) data is known: http://www.cs.princeton.edu/introcs/15inout/MovingAverage.java.html http://stackoverflow.com/questions/2161815/r-zoo-series-sliding-window-calculation http://taragana.blogspot.com/ http://www.dreamincode.net/forums/index.php?showtopic=92508 http://blogs.sun.com/nickstephen/entry/dtrace_and_moving_rolling_averages

    Read the article

  • need to generate unlimited number of unique id's with jQuery

    - by jquery n00b
    Hi all, extreme n00b here... I've got a number of elements (dynamically generated by back end so it could be quite a few) and all need a unique id. I'm trying to work out how to do this wth jQuery and not doing so well. Any help is appreciated. In the code below, I'd want each "bar" div to get a unique id, like id1, id2 etc etc <div class="foo"> <ul class="bar"> </ul> <ul class="bar"> </ul> <ul class="bar"> </ul> <ul class="bar"> </ul> </div>

    Read the article

  • Returning unique values of a multi-dimensional array with CodeIgniter PHP

    - by Michael Bradley
    Hi - I'm developing a property rentals website. The search results page will contain a list of property results. It is my intention to redefine the results, say by town, country, property type etc. So let's say for example the user searches 'France'. All of the relative properties will be returned and displayed in a list. However, I also need to reuse this array, to display only unique town names from the search results array. e.g. Montpellier, Lyon, Rennes, Nice etc. The idea is when use user click on 'Nice', only the 'Nice' properties would return. I would also like to display how many properties are in that town. The closest example as to what I want to achieve. http://www.miaandmaggie.com/dog-collars-leashes.html Any ideas how I can use my search array to display the unique towns of the search? Many thanks! M

    Read the article

  • Java array assignment (multiple values)

    - by Danny King
    Hello, I have a Java array defined already e.g. float[] values = new float[3]; I would like to do something like this further on in the code: values = {0.1f, 0.2f, 0.3f}; But that gives me a compile error. Is there a nicer way to define multiple values at once, rather than doing this?: values[0] = 0.1f; values[1] = 0.2f; values[2] = 0.3f; Thanks!

    Read the article

  • Unique keys for Sphinx along three vectors instead of two

    - by Brendon Muir
    I'm trying to implement thinking-sphinx across multiple 'sites' hosted under a single rails application. I'm working with the developer of thinking-sphinx to sort through the finer details and am making good progress, but I need help with a maths problem: Usually the formula for making a unique ID in a thinking-sphinx search index is to take the id, multiply it by the total number of models that are searchable, and add the number of the currently indexed model: id * total_models + current_model This works well, but now I also through an entity_id into the mix, so there are three vextors for making this ID unique. Could someone help me figure out the equation to gaurantee that the id's will never collide using these three variables: id, total_models, total_entities The entity ID is an integer. I thought of: id * (total_models + total_entities) + (current_model + current_entity) but that results in collisions. Any help would be greatly appreciated :)

    Read the article

  • C# ASP.NET update SQL database with values from text boxes

    - by Sir Graystar
    Here's what I have. User enters values into text boxes (personal information etc.) and then presses a save changes button. The values in these text boxes get stored in an SQL database. The problem I have is that when updating the database using the values from the text boxes, the page refreshes and the values in the text boxes are lost (or rather they return to the values that are already in the database as the data from the database is loaded into the text boxes on Page_Load). When I update the database using valuse stored in variables it all works fine. What is the best way to update with the values from the text boxes?

    Read the article

  • Removing duplicate SQL records to permit a unique key

    - by j pimmel
    I have a table ('sales') in a MYSQL DB which should have rightfully have had a unique constraint enforced to prevent duplicates. To first remove the dupes and set the constraint is proving a bit tricky. Table structure (simplified): 'id (unique, autoinc)' product_id The goal is to enforce uniqueness for product_id. The de-duping policy I want to apply is to remove all duplicate records except the most recently created, eg: the highest id Or to put another way, I would like to delete duplicate records, excluding the ids matched by the following query: select id from sales s inner join (select product_id, max(id) as maxId from sales group by product_id having count(product_id) > 1) groupedByProdId on s.product_id and s.id = groupedByProdId.maxId I've struggled with this on two fronts - writing the query to select the correct records to delete and then also the constraint in MYSQL where a subselect FROM clause of a DELETE cannot reference the same table from which data is being removed.

    Read the article

  • SQL Get Latest Unique Rows

    - by Simpleton
    I have a log table, each row representing an object logging its state. Each object has a unique, unchanging GUID. There are multiple objects logging their states, so there will be thousands of entries, with objects continually inserting new logs. Everytime an object checks in, it is via an INSERT. I have the PrimaryKey, GUID, ObjectState, and LogDate columns in tblObjects. I want to select the latest (by datetime) log entry for each unique GUID from tblObjects, in effect a 'snapshot' of all the objects. How can this be accomplished?

    Read the article

  • Finding unique elements in an string array in C

    - by LuckySlevin
    Hi, C bothers me with its handling of strings. I have a pseudocode like this in my mind: char *data[20]; char *tmp; int i,j; for(i=0;i<20;i++) { tmp = data[i]; for(j=1;j<20;j++) { if(strcmp(tmp,data[j]))//then except the uniqueness, store them in elsewhere. } } But when i coded this the results were bad.(I handled all the memory stuff,little things etc.) The problem is in the second loop obviously :D. But i cannot think any solution. How do i find unique strings in an array. Example input : abc def abe abc def deg entered unique ones : abc def abe deg should be found.

    Read the article

  • MySQL Many to Many with Unique keys and Update/Select if Exists otherwise Insert

    - by Jayrox
    In my goal to have a Many-to-Many relationship in my MySQL database I have arrived at another bridge to build. Current Tables: Users (id, name) Tags (id, name) User_Tags (user_id, tag_id) Here is the goal: I would like to have the ability to take a tag i.e: #fb and insert it into my Tags database which has a unique constraint on name and if the tag exists I would like to return it's id I would like to insert the tag.id and the current user's user.id into User_Tags. I do not have any unique constraints on the User_Tags table because I would like to be able to track the user's most commonly used tags and present them in a list ordered by frequency of use. I am currently developing this project in PHP using prepared statements. Additionally, performance is not currently an issue as my user count is still fairly small, but it is steadily growing and may be an issue in the future.

    Read the article

< Previous Page | 11 12 13 14 15 16 17 18 19 20 21 22  | Next Page >