MySQL变量,GROUP_CONCAT不起作用

时间:2013-04-23 08:03:52

标签: mysql

我遇到的问题是变量不等于输出。宠物有一个所有者,这会试图查看该主人是否有其他宠物并将它们组合在一起。

SELECT
o.id,
o.last_name,
@dog_names := GROUP_CONCAT(concat(p2.name,' (',REPLACE(REPLACE(p.type,'Big Dog','BD'),'Small Dog','LD'),')') SEPARATOR ', ') as dog_names,
@dog_names as dog_variable,
concat(o.last_name,' - ',@dog_names) as label
FROM pets p
LEFT JOIN owners o ON p.owner_id = o.id
LEFT JOIN pets p2 ON p.owner_id = p2.owner_id
WHERE p.name = 'wolfie'
GROUP BY o.id

输出如下:

id   | last_name | dog_names               | dog_variable | label
1647 | Reeve     | Wolfie (BD), Ember (BD) | Wolfie (BD)  | Reeve - Wolfie (BD)

为什么dog_variable与dog_names不匹配?

2 个答案:

答案 0 :(得分:2)

它们按相同级别计算,没有特定顺序。这就是SQL的工作原理:它是声明性的而不是程序性的,并且在任何查询中都不能在同一级别假设评估顺序。

换句话说,@dog_names as dog_variable将使用较旧的@dog_names值,因为如果没有为此次迭代重新评估

如果您希望它是理智的,那么重复表达式或使用嵌套查询

SELECT
   id, last_name,
   @dog_names := dog_names,
   @dog_names as dog_variable,
   concat(last_name,' - ', @dog_names) as label
FROM
    (
    SELECT
      o.id,
      o.last_name,
      GROUP_CONCAT(concat(p2.name,' (',REPLACE(REPLACE(p.type,'Big Dog','BD'),'Small Dog','LD'),')') SEPARATOR ', ') as dog_names
    FROM pets p
    LEFT JOIN owners o ON p.owner_id = o.id
    LEFT JOIN pets p2 ON p.owner_id = p2.owner_id
    WHERE p.name = 'wolfie'
    GROUP BY o.id, o.last_name
    ) x

说,为什么要使用GROUP_CONCAT变量?

答案 1 :(得分:0)

SELECT 
    o.id, 
    o.last_name, 
    @dog_names := GROUP_CONCAT(concat(p2.name,' (',REPLACE(REPLACE(p.type,'Big Dog','BD'),'Small Dog','LD'),')') SEPARATOR ', '),
    @dog_names as dog_names, 
    @dog_names as dog_variable, 
    concat(o.last_name,' - ',@dog_names) as label
FROM pets p
LEFT JOIN owners o ON p.owner_id = o.id
LEFT JOIN pets p2 ON p.owner_id = p2.owner_id
WHERE p.name = 'wolfie'
GROUP BY o.id