我想生成一个复杂的自连接查询抛出DQL。
这是我的表格结构的简单版本。
CREATE TABLE `item_view` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`id_item` int(11) NOT NULL,
`id_user` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
)
,实体将
/**
* @Column(name="id", type="integer", nullable=false)
* @Id
* @GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* @ManyToOne(targetEntity="User")
* @JoinColumns({
* @JoinColumn(name="id_user", referencedColumnName="id_user")
* })
*/
private $user;
/**
* @ManyToOne(targetEntity="Item")
* @JoinColumns({
* @JoinColumn(name="id_item", referencedColumnName="id_item")
* })
*/
private $item;
我很想生成像这样的查询:(
select
`c2`.*, count(`c1`.`id_user`) as `vc`
from
`item_view` `c1`
inner join
`item_view` `c2` ON `c1`.`id_user` = `c2`.`id_user`
where
`c1`.`id_item` in (6) and `c2`.`id_item` not in (6)
group by `c2`.`id_item`
order by `vc` desc
通过此本机查询,我可以选择常用的用户信息。
任何想法我们怎么做才能抛出DQL?
更新
我只是找到了解决桥梁关系的工作
SELECT v,COUNT(v.user) AS USR_CNT FROM ItemView v JOIN v.user u JOIN u.views v2
WHERE v2.item IN (:items) and v NOT IN (:items)
GROUP BY v.item
ORDER BY USR_CNT DESC
将生成此SQL
SELECT
`i0_`.`id` AS `id0`,
COUNT(`i0_`.`id_user`) AS `sclr2`,
`i0_`.`id_user` AS `id_user3`,
`i0_`.`id_item` AS `id_item4`
FROM
`item_view` `i0_`
INNER JOIN
`user` `u1_` ON `i0_`.`id_user` = `u1_`.`id_user`
INNER JOIN
`item_view` `i2_` ON `u1_`.`id_user` = `i2_`.`id_user`
WHERE
`i2_`.`id_item` IN (6) AND `i0_`.`id` NOT IN (6)
GROUP BY `i0_`.`id_item`
ORDER BY `sclr2` DESC
那么我们怎样才能消除用户表的额外连接?!