在mysql中选择具有相同id但具有不同列值的行

时间:2016-12-21 14:33:09

标签: mysql

我想选择具有不同行但ID相同的数据。

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

我想要的是获得分类为LETTER B的行,还有使用相同Codenum的LETTER A的描述。

不完整的查询是SELECT description FROM table where letter = B,我想添加与Codenum对应的字母A的描述 期望的结果:

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

提前多多感谢

4 个答案:

答案 0 :(得分: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'

答案 1 :(得分: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'

答案 2 :(得分:0)

我认为你要找的是group_concat()

尝试此查询:

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

答案 3 :(得分: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'