简体   繁体   中英

SQL Multiple Select Based on Key on a single table

Thanks in advance if anyone here can answer. I have this two tables:

      Strings                Numbers
 ----------------        ----------------
| ID  |  String  |      | ID  |  Number  |
 ----------------        ----------------
|  1  |    'A'   |      |  1  | 'First'  |
|  1  |    10    |      |  2  | 'Second' |
 ----------------       |  3  | 'Third'  |
|  2  |    'B'   |      |  4  | 'Fourth' |
|  2  |    11    |      |  5  | 'Fifth'  |
 ----------------        ----------------
|  3  |    'A'   |
|  3  |    12    |
 ----------------
|  4  |    'B'   |
|  4  |    13    |
 ----------------
|  5  |    'B'   |
|  5  |    14    |
 ----------------

For example, I filter the values "associated" with 'A', I have to get a table like this:

     Strings
 ----------------
| ID  |  String  |
 ---------------- 
|  1  |    10    |
 ---------------- 
|  3  |    12    |
 ----------------

And for instance, If wanna filter the values "associated" with 'B', I have to get a table like this:

      Strings
 ----------------
| ID  |  String  |
 ---------------- 
|  2  |    11    |
 ----------------
|  4  |    13    |
 ----------------
|  5  |    14    |
 ----------------

Again, thanks if you can help me.

Unless I am missing something you would use:

select s1.id, s1.string
from strings s1
inner join strings s2
    on s1.id = s2.id
    and s1.string != 'A'
    and s2.string = 'A'

See SQL Fiddle with Demo

Or

select s1.id, s1.string
from strings s1
inner join strings s2
    on s1.id = s2.id
    and s1.string != 'B'
    and s2.string = 'B'

See SQL Fiddle with Demo

SELECT * FROM Strings WHERE string = "A"

*视情况替换*的字段名称。

select s2.ID,
       s2.String
  from Strings as s1
 inner join Strings as s2
    on s2.id = s1.id
   and s2.String != s1.String
 where s1.String = ?

However, this table structure is questionable. ID seems like it should be the primary key, but it can't be since there are multiple values. Also you never need the Numbers table so why include it in the question? :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM