我有以下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);
但是没有显示结果。
答案 0 :(得分: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);
完成,问题解决了。