sql查询显示此结果

时间:2011-02-20 07:32:03

标签: sql mysql

我需要一些帮助才能在sql中进行查询

假设我有:表名:register

    **id_r   |    name    |    text    |**
        1    |    name 1  |    text 1  |
        2    |    name 2  |    text 2  |

和表名:详细信息

**id_d    |    id_r    |    text_d    |**
     1    |      1     |     text 1a  |
     2    |      1     |     text 1b  |
     3    |      2     |     text 2a  |

我需要的结果如下:

**id_r    |    name    |    text    |     text_d_a    |    text_d_b    |**
  1       |   name 1   |    text 1  |     text 1a     |    text 1b     |
  2       |   name 2   |    text 2  |     text 2a

我怎么能用sql语句来做这样的事情?

2 个答案:

答案 0 :(得分:0)

有可能:

SELECT
    R.id_r, R.name, R.[text], 
    D1.text_d AS 'text_d_a', 
    D2.text_d AS 'text_d_b'
FROM 
    register R
    LEFT JOIN details D1 ON R.id_r = D1.id_r AND D1.text_d LIKE '%a%'
    LEFT JOIN details D2 ON R.id_r = D2.id_r AND D2.text_d LIKE '%b%'

答案 1 :(得分:0)

我认为使用此结构是个坏主意,因为您的查询将取决于表数据。您可以使用逗号来压缩text_d值,例如:

SELECT t1.*, 
      (SELECT GROUP_CONCAT(t2.`text_d` SEPARATOR ',') FROM `details` as t2 
       WHERE t2.`id_r`=t1.`id_r`) as `text_d`
FROM `register` as t1