我有4个具有以下模式的表。
我正在尝试从Iposts获得所有详细信息,这些产品可能已附加或未附加更多产品。如果有,请从产品中获取详细信息。 到目前为止的代码:
SELECT ip.*,
sf.profile_picture,
sf.NAME AS page_title,
sf.profile_username,
FROM iposts ip
INNER JOIN ipostssf sf
ON sf.page_id = ip.inst_user_id
LEFT JOIN products p
ON p.id IN
(
SELECT ipp.product_id
FROM ipostproduct ipp
WHERE ipp.id = ip.id)
WHERE ip.user_id = 1
AND sf.status = 1 ');
试图选择介绍子选择
SELECT ip.*,
sf.profile_picture,
sf.NAME AS page_title,
sf.profile_username,
(SELECT p.*
FROM products p
WHERE p.id IN (SELECT ipp.product_id
FROM ipostsproduct ipp
WHERE ipp.post_id = p.id))
FROM iposts ip
INNER JOIN ipostssf sf
ON sf.page_id = ip.inst_user_id
最终数组将类似于
$arr = array(
'profile_picture'=>...,
'page_title' => ....,
'profile_username' => ....,
'products' => array(
'1' => array(
//all the details here
'id'=> ....,
'handle' => ...,
),
'2' => array(
//all the details here
'id'=> ....,
'handle' => ...,
)
)
);
我可以从iposts内部联接中选择ipostssf左联接ipostsproduct(它可能具有/否),但是如果有,我如何才能将ipostsproduct与具有产品ID的产品进行内部联接。
P.S问题不是如何检索json / array,而是如何执行查询,以使结果包含使用联接的每个表中的所有产品和所有产品详细信息。