2016-12-21 232 views
1

我想選擇具有不同行但ID相同的數據。在mysql中選擇具有相同id但具有不同列值的行

| Codenum | Letter | description | 
|  001 | A  | APPLES  | 
|  002 | A  | BANANA  | 
|  001 | B  | RED   | 
|  001 | B  | GREEN  | 
|  002 | B  | BLUE  | 
|  002 | B  | YELLOW  | 

我想得到的是分類爲信件B的行,但也有相同的Codenum的信件A的描述。

不完整的查詢SELECT description FROM table where letter = B,我想添加字母A,與Codenum 期望的結果所對應的描述:

001 B RED  APPLES 
001 B GREEN APPLES 
002 B BLUE BANANA 
002 B YELLOW BANANA 

感謝很多提前

+0

剛剛加入該表本身 – Strawberry

+0

它說不是唯一表 – OFBrc

回答

0

試試這個

select a.codenum, a.letter, a.description, b.description 
from table a join table b 
    on b.codenum = a.codenum 
     and b.letter = 'A' 
where a.letter = 'B' 
+0

嗨。他們在同一張桌子上 – OFBrc

+0

@OFBrc沒有提供與答案相矛盾的事實。 – Strawberry

0

我覺得你要找的是group_concat()

試用此查詢:

SELECT 
    GROUP_CONCAT(`description`) as description_concat 
FROM 
    `table_name` 
WHERE 
    `letter` = 'B' 
GROUP BY 
    `letter` 
0

精確查詢:

select a.codenum, a.letter, a.description,b.description 
from tbl_data a join tbl_data b on b.codenum = a.codenum 
and b.letter = 'A' where a.letter = 'B' 
1

你可以用一個子查詢做到這一點:

SELECT Codenum, Letter, description, (SELECT description FROM mytable x where x.Codenum = second.Codenum AND Letter = 'A') AS adescription 
FROM mytable second 
WHERE mytable.Letter = 'B' 
相關問題