2012-06-08 24 views
0

我有這樣MySQL的聯接提取數

id user type comment 
    6 1 A id '3' - #8 
    7 1 A id '3' - #9 
    8 3 B  
    9 3 B 

我想散後提取號碼,並與id列加入它有以下一個「大」表(當單間數量報價等於用戶)

id1 id2 user type 
    6 8 3  B 
    7 9 3  B 
+0

任何共同的領域?你可以把表結構? – jcho360

+0

id和用戶(int 11),類型和註釋(varchar 55) – moeezed

回答

0

一個創建表的副本,它的名字是BigTable中並插入你給了我們這些值:

mysql> create table bigtable (id int, user_id int, type varchar(10), comment varchar(30)); 
Query OK, 0 rows affected (0.04 sec) 

mysql> insert into bigtable values (6,1, 'A', 'id 3 - #8'),(7,1,'A', 'id 3 - #9'),(8,3, 'B',''),(9,3, 'B',''); 
Query OK, 4 rows affected (0.01 sec) 
Records: 4 Duplicates: 0 Warnings: 0 

mysql> select * from bigtable; 
+------+---------+------+-----------+ 
| id | user_id | type | comment | 
+------+---------+------+-----------+ 
| 6 |  1 | A | id 3 - #8 | 
| 7 |  1 | A | id 3 - #9 | 
| 8 |  3 | B |   | 
| 9 |  3 | B |   | 
+------+---------+------+-----------+ 
4 rows in set (0.00 sec) 

我做了一個自連接,並使用substrn_index功能:

mysql> select b1.id,b2.id,b1.user_id,b1.type 
from bigtable as b1 join bigtable as b2 
on b1.id=SUBSTRING_INDEX(b2.COMMENT,'#',-1); 
+------+------+---------+------+ 
| id | id | user_id | type | 
+------+------+---------+------+ 
| 8 | 6 |  3 | B | 
| 9 | 7 |  3 | B | 
+------+------+---------+------+ 
2 rows in set (0.00 sec) 

我希望這有助於你

+0

它的工作,謝謝:) – moeezed

+0

哈哈我很高興!,快樂的週末 – jcho360