1

如何组合以下两个 mySQL select 语句,以便将每个语句放在不同的列但在同一个表中?

select a.property as p1 from T1 a inner join T2 b on a.id = b.id1;

select a.property as p2 from T1 a inner join T2 b on a.id = b.id2;

这些语句中的每一个都单独工作,并将返回相同数量的行。我只想在同一张表中的两列中获得两个结果。

4

2 回答 2

2

在这样的单个语句中使用它

select 
     case when a.id=b.id1 then a.property end as p1,
     case when a.id=b.id2 then a.property end as p2
from 
     T1 a inner join T2 b on a.id in (b.id1,b.id2)
于 2012-07-23T09:28:42.193 回答
0

您可以使用此解决方案:

SELECT
    a.property AS p1, b.property AS p2
FROM
(
    SELECT a.property, @rn1:=@rn1+1 AS rn
    FROM T1 a
    INNER JOIN T2 b ON a.id = b.id1
    CROSS JOIN (SELECT @rn1:=0) var_init
) a
INNER JOIN
(
    SELECT a.property, @rn2:=@rn2+1 AS rn
    FROM T1 a
    INNER JOIN T2 b ON a.id = b.id2
    CROSS JOIN (SELECT @rn2:=0) var_init
) b ON a.rn = b.rn

编辑:这是 Madhivanan 解决方案的变体,应该更简单:

SELECT   MAX(CASE WHEN a.id=b.id1 THEN a.property END) AS p1,
         MAX(CASE WHEN a.id=b.id2 THEN a.property END) AS p2
FROM     T1 a 
JOIN     T2 b ON a.id IN (b.id1,b.id2)
GROUP BY a.id

我们添加了 GROUP BY 和 MAX,这样我们就不会得到两行id,我们只选择 case 表达式的最大值,它为每个组获取非空值(基本上将每列中的属性放在同一每个行id)。

于 2012-07-23T09:40:58.167 回答