I want to write sub-query with right join of sql in cake php , query below
SELECT stkid,s.id as stk_id, s.userid as stk_userid,
s.productid as productid, u.id as userid
FROM (select * FROM stocks as st where st.`productid` = 1) as s
right join users as u on (u.id = s.userid)
group by u.id
please help me out with this any help or suggestion would be appreciated
First, I have to say your SQL query is not optimised : your FROM sub-query is useless.
Take a look :
SELECT
stkid,
s.id AS stk_id,
s.userid AS stk_userid,
s.productid AS productid,
u.id AS userid
FROM stocks AS s
RIGHT JOIN users AS u
ON u.id = s.userid
WHERE s.productid = 1
GROUP BY u.id
The "I just want the answer of this sql", and the simple way is this (in controller) :
// get the DB link
$pdo = $this->ModelOfThisController->getDataSource()->getConnection();
$sql = "SELECT
stkid,
s.id AS stk_id,
s.userid AS stk_userid,
s.productid AS productid,
u.id AS userid
FROM (
SELECT *
FROM stocks AS st
WHERE st.`productid` = 1
) AS s
RIGHT JOIN users AS u
ON (u.id = s.userid)
GROUP BY u.id
";
$req = $pdo->prepare($sql);
$req->execute(array(
// ':param1' => $param1,
// ':param2' => $param2,
));
$data = $req->fetch(PDO::FETCH_ASSOC);
// ...
The other way is with cakePHP ORM but I don't think you can change the FROM to anything else than the models' table name...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.