I’ve got a MySQL table like the following:
+--------------------------------------------+
| ID | State | Name | City |
+--------------------------------------------+
| PA1 | PA | Foo | Philly |
| VA1 | PA | Foo | Philly |
| DC1 | VA | Foobar | Washington |
| ME2 | ME | Barfoo | Portland |
+--------------------------------------------+
Now, I want to do a SELECT statement where I SELECT only those rows where State = SUBSTR(ID, 1, 2), unless the Name only appears in the table one time. In other words, I want to end up with the following table:
+--------------------------------------------+
| ID | State | Name | City |
+--------------------------------------------+
| PA1 | PA | Foo | Philly |
| DC1 | VA | Foobar | Washington |
| ME2 | ME | Barfoo | Portland |
+--------------------------------------------+
In the second row, the State does not equal the substring of ID and that ‘Name’ (“Foo”, in this example) appears in the table more than once, so we don’t get that row. However, I also want the third row, even though State again does not equal the substring of ID, because that ‘Name’ only appears once in the original table.
Any ideas as to what query I could use to achieve this? I’ve been playing around with it for quite some time without success. Thanks!
1 Answer