0

我有以下mysql查询

SELECT
    *
FROM
(
    SELECT
        CASE WHEN t2.user1=1 THEN t2.user2 ELSE t2.user1 END AS userId
    FROM
        t AS t2
    WHERE 1 IN (t2.user1,t2.user2)
    AND t2.[status]=1
) as tbl
WHERE EXISTS 
(
    SELECT
        NULL
    FROM
        t
    WHERE 2 IN (t.user1,t.user2)
    AND tbl.userId=(CASE WHEN t.user1=2 THEN t.user2 ELSE t.user1 END)
    AND t.[status]=1
)

它工作正常,但我无法将其转换为 Doctrine2 查询。

知道怎么做吗?

http://sqlfiddle.com/#!2/4c792/11

[编辑] 我使用 Native SQL 来执行查询。

$rsm = new ResultSetMapping();
$rsm->addEntityResult('myProject\DataBundle\Entity\Friend', 'f');

    $sql= '
    SELECT
             *
        FROM (
            SELECT 
                CASE WHEN t2.user1=2 THEN t2.user2 ELSE t2.user1 END AS userId
            FROM friends AS t2 
            WHERE 2 IN (t2.user1,t2.user2) 
            AND t2.status=1 
        ) as tbl 
        WHERE EXISTS (
        SELECT 
            NULL 
        FROM 
            friends as t
        WHERE 3 IN (t.user1,t.user2) 
        AND tbl.userId=(CASE WHEN t.user1=3 THEN t.user2 ELSE t.user1_id END) 
        AND t.isFriendOrFollower=1 )';

    $query = $this->getEntityManager()
        ->createNativeQuery($sql,$rsm);

但是没有显示结果。

4

1 回答 1

0

我找到了一种使用 dbal 更简单的方法。

1:你必须得到连接

$conn=$this->container->get('database_connection');

2:编写查询

$sql= '
    SELECT
             *
        FROM (
            SELECT 
                CASE WHEN t2.user1=2 THEN t2.user2 ELSE t2.user1 END AS userId
            FROM friends AS t2 
            WHERE 2 IN (t2.user1,t2.user2) 
            AND t2.status=1 
        ) as tbl 
        WHERE EXISTS (
        SELECT 
            NULL 
        FROM 
            friends as t
        WHERE 3 IN (t.user1,t.user2) 
        AND tbl.userId=(CASE WHEN t.user1=3 THEN t.user2 ELSE t.user1_id END) 
        AND t.isFriendOrFollower=1 )';

3:执行查询。

$rows = $conn->fetchAll($sql);

完成,问题解决。

于 2013-02-19T04:26:50.220 回答