如何从加入的MySQL表中进行选择?

时间:2009-12-28 17:42:54

标签: sql mysql

我基本上有两张桌子:

A(id int, name varchar(10), info varchar(10))
B(id int, item varchar(10))

A
1 A Hello
2 B World
3 C Foo

B
1 apple
1 orange
1 hammer
2 glass
2 cup

使用以下查询...

mysql> SELECT a.id, a.name, a.info, group_concat(b.item SEPARATOR ' ')
       FROM a
       LEFT OUTER JOIN b ON (a.id=b.id)
       GROUP BY 1,2,3;

我得到了所需的输出:

+------+------+-------+------------------------------------+
| id   | name | info  | group_concat(b.item separator ' ') |
+------+------+-------+------------------------------------+
|    1 | A    | Hello | apple orange hammer                | 
|    2 | B    | World | glass cup                          | 
|    3 | C    | Foo   | NULL                               | 
+------+------+-------+------------------------------------+

我现在想修改查询以获取包含相同信息的结果表,但只包含那些以字母o开头的项目,(like 'o%')如何获得以下输出?

+------+------+-------+------------------------------------+
| id   | name | info  | group_concat(b.item separator ' ') |
+------+------+-------+------------------------------------+
|    1 | A    | Hello | apple orange hammer                |                        
+------+------+-------+------------------------------------+

请注意,我仍然想要呈现整个字符串'apple orange hammer',而不仅仅是'orange'

5 个答案:

答案 0 :(得分:2)

SELECT  a.id, a.name, a.info, group_concat(b.item SEPARATOR ' ') AS bs
FROM    a
LEFT OUTER JOIN
        b
ON      b.id = a.id
GROUP BY
        id, name, info
HAVING   
        bs RLIKE '[[:<:]]o'

或者这(更有效率):

SELECT  a.id, a.name, a.info,
        (
        SELECT  GROUP_CONCAT(b.item SEPARATOR ' ') AS bs
        FROM    b
        WHERE   b.id = a.id
        ) AS bs
FROM    (
        SELECT  DISTINCT b.id
        FROM    b
        WHERE   item LIKE 'o%'
        ) q
JOIN    a
ON      a.id = q.id

如果您在b (item, id)

上有复合索引,则后一个查询会更快

答案 1 :(得分:1)

SELECT a.id, a.name, a.info, group_concat(b.item SEPARATOR ' ')
FROM a
LEFT OUTER JOIN b ON (a.id=b.id)
WHERE a.id in (select id from b where upper(SUBSTRING(b.item,0,1)) = 'O')
GROUP BY 1,2,3

答案 2 :(得分:1)

另一种方法:

SELECT a.id, a.name, a.info, group_concat(b.item SEPARATOR ' ') AS items
   FROM a
   LEFT OUTER JOIN b ON (a.id=b.id)
   GROUP BY 1,2,3
   HAVING items REGEXP '[[:<:]]o';

答案 3 :(得分:0)

SELECT * FROM
  (SELECT a.id, a.name, a.info, group_concat(b.item SEPARATOR ' ')
  FROM a
  LEFT OUTER JOIN b ON (a.id=b.id)
  GROUP BY 1,2,3)
WHERE a.id IN (SELECT bb.id FROM b AS bb WHERE name like 'o%');

我怀疑这种表现不错,但对我而言似乎合乎逻辑。

答案 4 :(得分:0)

在你需要在group_concat上使用like运算符后,你需要使用该组。

Group By 1,2,3
HAVING group_concat(b.item SEPARATOR ' ') like ('%o%')

请注意我只是在寻找您需要根据您的要求调整类似声明的任何内容。