gpt4 book ai didi

mysql - 如何在 zend db 上构建嵌套选择

转载 作者:行者123 更新时间:2023-11-29 13:29:08 25 4
gpt4 key购买 nike

您好,我在执行此查询时遇到问题

SELECT * FROM(
SELECT `b`.*,`owner`.firstname,`owner`.lastname,`owner`.email,
(
SELECT COUNT(`ps`.profile_id) FROM `profile` AS `ps`
LEFT JOIN `xref_store_profile_brand` AS `xbp` ON `xbp`.profile_id = `ps`.profile_id
WHERE `xbp`.brand_id = b.brand_id AND ps.role = 'salesrep' AND `xbp`.store_id IS NULL
) AS `salesrepTotal`,
(
SELECT GROUP_CONCAT(`ms`.firstname) FROM `profile` AS `ps`
LEFT JOIN `xref_store_profile_brand` AS `xbp` ON `xbp`.profile_id = `ps`.profile_id
LEFT JOIN `member` AS `ms`ON `ms`.member_id = `ps`.member_id
WHERE `xbp`.brand_id = `b`.brand_id AND ps.role = 'salesrep' AND `xbp`.store_id IS NULL
) AS `salesrep`,
(
SELECT COUNT(`s`.store_id) FROM `store` AS `s`
LEFT JOIN `xref_store_profile_brand` AS `xbs` ON `xbs`.store_id = `s`.store_id
WHERE `xbs`.brand_id = `b`.brand_id AND `xbs`.brand_id IS NOT NULL
) AS `storeTotal`,
(
SELECT GROUP_CONCAT(`s`.name) FROM `store` AS `s`
LEFT JOIN `xref_store_profile_brand` AS `xbs` ON `xbs`.store_id = `s`.store_id
WHERE `xbs`.brand_id = `b`.brand_id AND `xbs`.brand_id IS NOT NULL
) AS `store`

FROM `brand` AS `b`
LEFT JOIN
(
SELECT `m`.firstname,`m`.lastname,`m`.email,`xspb`.brand_id FROM `member` AS `m`
LEFT JOIN `profile` as `p` ON `p`.member_id = `m`.member_id AND `p`.role = 'designer' AND `p`.isPrimary = 1
LEFT JOIN `xref_store_profile_brand` AS `xspb` ON `xspb`.profile_id = `p`.profile_id AND `xspb`.store_id IS NULL
) AS `owner` ON `owner`.brand_id =`b`.brand_id

GROUP BY `b`.brand_id
) AS `final`

如何将其转换为 Zend_Db_Select 对象?

主要问题是这部分

SELECT `b`.*,`owner`.firstname,`owner`.lastname,`owner`.email,
(
SELECT COUNT(`ps`.profile_id) FROM `profile` AS `ps`
LEFT JOIN `xref_store_profile_brand` AS `xbp` ON `xbp`.profile_id = `ps`.profile_id
WHERE `xbp`.brand_id = b.brand_id AND ps.role = 'salesrep' AND `xbp`.store_id IS NULL
) AS `salesrepTotal`,

最佳答案

您需要使用Zend_Db_Expr您查询中的对象和 array structures for select AS .

以下是您正在寻找的解决方案:

<?php

$db = Zend_Db_Table::getDefaultAdapter();

// inner query
$sqlSalesRepTotal = $db->select()
->from(array('ps' => 'profile'))
->joinLeft(array('xbp' => 'xref_store_profile_brand'), 'xbp.profile_id = ps.profile_id')
->where('xbp.brand_id = b.brand_id')
->where('ps.role = ?', 'salesrep')
->where('xbp.store_id IS NULL');

// main query
$sql = $db->select()
->from(array('b' => 'brand'), array(
// NOTE: have to add parentesis around the expression
'salesrepTotal' => new Zend_Db_Expr("($sqlSalesRepTotal)")
))
->where('....')
->group('brand_id');


// debug
var_dump($db->fetchAll($sql));

关于mysql - 如何在 zend db 上构建嵌套选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19727859/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com