Using My SQL joins - php

I am having trouble finishing my MySQL JOIN. I am unsure of the syntax for the last part of my query.
My Query:
$posts_query= "
SELECT *
FROM posts p
JOIN relations r ON p.user_id = r.recipient
WHERE (r.status = 1 OR r.status = 2)
AND (r.sender = '".$user_id."' OR p.user_id = '".$user_id."')
// How do I write this part?
AND skip where r.status = 1 and p.privacy = 2 where p.user_id != $user_id //
ORDER BY p.post_id DESC;
";

Instead of 'skip', just set it so that the value isn't true, using NOT:
SELECT *
FROM posts p
JOIN relations r ON p.user_id = r.recipient
WHERE (r.status = 1 OR r.status = 2)
AND (r.sender = '$user_id' OR p.user_id = '$user_id')
AND NOT (r.status = 1 AND p.privacy = 2 AND p.user_id != '$user_id')
ORDER BY p.post_id DESC;"

SELECT *
FROM posts p
JOIN relations r ON p.user_id = r.recipient
WHERE r.status in (1,2)
AND (r.sender = '$user_id' OR p.user_id = '$user_id')
AND NOT ( r.status = 1 and p.privacy = 2 AND p.user_id != '$user_id' )
ORDER BY p.post_id DESC;

Related

Add count in joins from another table in mysql

I am getting some records by joining three tables in MYSQL. The records I am getting is correct. But now I have to add one more table in this query where I have to get the unread messages for the logged in users.
Here is the query which I am using
SELECT c.c_id, u.id AS user_id, u.first_name, u.last_name, u.user_name, u.online_status, u.user_img, c.property_id, p.locality, p.city
FROM cpo_conversation c, property_register u, property_for_sale p
WHERE CASE WHEN c.user_one = '19'
THEN c.user_two = u.id
WHEN c.user_two = '19'
THEN c.user_one = u.id
END AND (
c.user_one = '19'
OR c.user_two = '19'
)
AND p.id = c.property_id
ORDER BY c.c_id DESC
Here is my fourth table po_conversation_reply
I want to add this table's read_unread_status count for every user who is logged in. I tried something but this is giving me the same result for every user
SELECT (
SELECT COUNT( * )
FROM cpo_conversation_reply
WHERE user_id_fk = u.id
AND read_unread_status =0
) AS your_count, c.c_id, u.first_name, u.last_name, u.user_name, u.online_status, c.user_one, c.user_two, u.user_img, c.property_id, p.locality, p.city
FROM cpo_conversation c, property_register u, property_for_sale p
WHERE CASE WHEN c.user_one = '19'
THEN c.user_two = u.id
WHEN c.user_two = '19'
THEN c.user_one = u.id
END AND (
c.user_one = '19'
OR c.user_two = '19'
)
AND p.id = c.property_id
ORDER BY c.c_id DESC

7 query with inner join into 1 query, mysql

i have a question, how do i make totally 7 query into 1 query? to make the db query lesser? i have 1 table contain all of it, but the suggest is a "separator", each suggest i have to load 33 rows and order by dateline, i have think about use any inner join ... etc, but i think that is not a way? correct me if i'm wrong. Would Appreciate for help!THanks!!
This is the mysql query 1
$query = DB::query("SELECT t.*, d.did AS dingid, d.id AS dingpid, f.id AS bookmark, f.uid AS buid
FROM ".DB::table('comeing_tao')." AS t
LEFT JOIN ".DB::table('comeing_tao_ding')." AS d ON t.id = d.id AND d.uid = ".$_G['uid']."
LEFT JOIN ".DB::table('comeing_tao_fans')." AS f ON t.id = f.id AND f.uid = ".$_G['uid']."
WHERE t.suggest = 0 AND t.state = 1 ORDER BY dateline DESC LIMIT 33");
This is the mysql query 2
$query = DB::query("SELECT t.*, d.did AS dingid, d.id AS dingpid, f.id AS bookmark, f.uid AS buid
FROM ".DB::table('comeing_tao')." AS t
LEFT JOIN ".DB::table('comeing_tao_ding')." AS d ON t.id = d.id AND d.uid = ".$_G['uid']."
LEFT JOIN ".DB::table('comeing_tao_fans')." AS f ON t.id = f.id AND f.uid = ".$_G['uid']."
WHERE t.suggest = 1 AND t.state = 1 ORDER BY dateline DESC LIMIT 33");
This is the mysql query 3
$query = DB::query("SELECT t.*, d.did AS dingid, d.id AS dingpid, f.id AS bookmark, f.uid AS buid
FROM ".DB::table('comeing_tao')." AS t
LEFT JOIN ".DB::table('comeing_tao_ding')." AS d ON t.id = d.id AND d.uid = ".$_G['uid']."
LEFT JOIN ".DB::table('comeing_tao_fans')." AS f ON t.id = f.id AND f.uid = ".$_G['uid']."
WHERE t.suggest = 2 AND t.state = 1 ORDER BY dateline DESC LIMIT 33");
This is the mysql query 3
$query = DB::query("SELECT t.*, d.did AS dingid, d.id AS dingpid, f.id AS bookmark, f.uid AS buid
FROM ".DB::table('comeing_tao')." AS t
LEFT JOIN ".DB::table('comeing_tao_ding')." AS d ON t.id = d.id AND d.uid = ".$_G['uid']."
LEFT JOIN ".DB::table('comeing_tao_fans')." AS f ON t.id = f.id AND f.uid = ".$_G['uid']."
WHERE t.suggest = 3 AND t.state = 1 ORDER BY dateline DESC LIMIT 33");
This is the mysql query 4
$query = DB::query("SELECT t.*, d.did AS dingid, d.id AS dingpid, f.id AS bookmark, f.uid AS buid
FROM ".DB::table('comeing_tao')." AS t
LEFT JOIN ".DB::table('comeing_tao_ding')." AS d ON t.id = d.id AND d.uid = ".$_G['uid']."
LEFT JOIN ".DB::table('comeing_tao_fans')." AS f ON t.id = f.id AND f.uid = ".$_G['uid']."
WHERE t.suggest = 4 AND t.state = 1 ORDER BY dateline DESC LIMIT 33");
and so on... i skip the following 3 query cos is totally same except the t.suggest = 5, t.suggest = 6, t.suggest = 7
the goal is all the query in one, then play around with the array.
you can use OR
(t.suggest=3 OR t.suggest=4 OR ...) AND ...
if you want max 33 records from each suggest, try UNION
(SELECT ...) UNION (SELECT ...) UNION (SELECT ...) ...
TRY in clause
SELECT
t.*, d.did AS dingid, d.id AS dingpid, f.id AS bookmark, f.uid AS buid
FROM
".DB::table('comeing_tao')." AS t
LEFT JOIN ".DB::table('comeing_tao_ding')." AS d ON t.id = d.id AND d.uid =
".$_G['uid']."
LEFT JOIN ".DB::table('comeing_tao_fans')." AS f ON t.id = f.id AND f.uid =
".$_G['uid']."
WHERE
t.suggest IN(0,1,2,3,4,5,6,7)
AND
t.state = 1
ORDER BY
dateline DESC
but Limit will not give 33 records for each but 33 for whole return

Express query using doctrine query builder

I have the following query that I would like to convert to use doctrine's query builder.
SELECT
u.user_id,
u.username,
u.create_date AS join_date,
u.last_login_date,
u.membership_level,
u.create_date,
avg(round((ug.toggle_count / ceil((g.ply_count + 1) / 2)) * 100, 1)) AS __avg_toggle_ratio,
count(g.game_id) AS __game_count,
ugse.rating AS __echess_rating,
ugse.total_win_count AS __echess_win_count,
ugse.total_loss_count AS __echess_loss_count,
ugse.total_draw_count AS __echess_draw_count,
(SELECT concat(ugsl.rating,'|',ugsl.total_win_count,'|',ugsl.total_loss_count,'|',ugsl.total_draw_count) FROM user_game_stats_live ugsl WHERE ugsl.user_id = u.user_id AND ugsl.game_time_class = 'lightning') AS __lightning_data,
(SELECT concat(ugsl.rating,'|',ugsl.total_win_count,'|',ugsl.total_loss_count,'|',ugsl.total_draw_count) FROM user_game_stats_live ugsl WHERE ugsl.user_id = u.user_id AND ugsl.game_time_class = 'blitz') AS __blitz_data,
(SELECT concat(ugsl.rating,'|',ugsl.total_win_count,'|',ugsl.total_loss_count,'|',ugsl.total_draw_count) FROM user_game_stats_live ugsl WHERE ugsl.user_id = u.user_id AND ugsl.game_time_class = 'standard') AS __standard_data,
(SELECT uts.rating FROM user_tactics_settings uts WHERE uts.user_id = u.user_id AND uts.attempt_count >= 10) AS __tactics_rating
FROM
game g
JOIN user_game ug ON g.game_id = ug.game_id
JOIN user_game_stats_email ugse ON ug.user_id = ugse.user_id
JOIN user u ON ug.user_id = u.user_id
WHERE
g.last_move_time >= DATE_SUB(NOW(), INTERVAL 5 DAY) AND
g.ply_count >= 20 AND
u.is_enabled = 1
GROUP BY
ug.user_id
HAVING
__avg_toggle_ratio >= 90 AND
__game_count >= 10
ORDER BY
__avg_toggle_ratio DESC
Is the query builder capable of rewriting this kind of query? Should I use other methods instead, if so, how?
I'm not sure about query builder, but I woyld use the 'createNativeQuery' method:
<?php
use Doctrine\ORM\Query\ResultSetMapping;
$rsm = new ResultSetMapping();
// build rsm here
$query = $entityManager->createNativeQuery("SELECT
u.user_id,
u.username,
u.create_date AS join_date,
u.last_login_date,
u.membership_level,
u.create_date,
avg(round((ug.toggle_count / ceil((g.ply_count + 1) / 2)) * 100, 1)) AS __avg_toggle_ratio,
count(g.game_id) AS __game_count,
ugse.rating AS __echess_rating,
ugse.total_win_count AS __echess_win_count,
ugse.total_loss_count AS __echess_loss_count,
ugse.total_draw_count AS __echess_draw_count,
(SELECT concat(ugsl.rating,'|',ugsl.total_win_count,'|',ugsl.total_loss_count,'|',ugsl.total_draw_count) FROM user_game_stats_live ugsl WHERE ugsl.user_id = u.user_id AND ugsl.game_time_class = 'lightning') AS __lightning_data,
(SELECT concat(ugsl.rating,'|',ugsl.total_win_count,'|',ugsl.total_loss_count,'|',ugsl.total_draw_count) FROM user_game_stats_live ugsl WHERE ugsl.user_id = u.user_id AND ugsl.game_time_class = 'blitz') AS __blitz_data,
(SELECT concat(ugsl.rating,'|',ugsl.total_win_count,'|',ugsl.total_loss_count,'|',ugsl.total_draw_count) FROM user_game_stats_live ugsl WHERE ugsl.user_id = u.user_id AND ugsl.game_time_class = 'standard') AS __standard_data,
(SELECT uts.rating FROM user_tactics_settings uts WHERE uts.user_id = u.user_id AND uts.attempt_count >= 10) AS __tactics_rating
FROM game g
JOIN user_game ug ON g.game_id = ug.game_id
JOIN user_game_stats_email ugse ON ug.user_id = ugse.user_id
JOIN user u ON ug.user_id = u.user_id
WHERE g.last_move_time >= DATE_SUB(NOW(), INTERVAL 5 DAY)
AND g.ply_count >= 20
AND u.is_enabled = 1
GROUP BY ug.user_id
HAVING __avg_toggle_ratio >= 90
AND __game_count >= 10
ORDER BY __avg_toggle_ratio DESC', $rsm);
$query->setParameter(1, 'romanb');
$data = $query->getResult();

Yii CDbCommandBuilder query

I'm trying to perform a query in Yii with CDbCommandBuilder so I can have the resultset in an array.
Problem is that I don't understand how to convert my SQL (pgsql) to the Yii CDbCommandBuilder syntax. Mainly my problem is with nested joins.
The query:
SELECT p.id
up.id as fid,
sum(CASE
WHEN v1.count>v2.count THEN v2.count
ELSE v1.count
END
) as res
FROM product as v1
INNER JOIN (
SELECT p_id, count
FROM product
WHERE user_id = {$user_id}) as v2 on v1.p_id = v2.p_id and v1.user_id <> {$user_id}
RIGHT JOIN users as p on p.id = v1.user_id
INNER JOIN uf on uf.friend_id = p.id and uf.user_id = {$user_id} and is_active = true
INNER JOIN up on up.user_id = p.id and is_active = true
GROUP BY p.id, up.id
ORDER BY res desc
Can anyone help?
Thanks
$sql = "SELECT p.id
up.id as fid,
sum(CASE
WHEN v1.count>v2.count THEN v2.count
ELSE v1.count
END
) as res
FROM product as v1
INNER JOIN (
SELECT p_id, count
FROM product
WHERE user_id = :user_id) as v2 on v1.p_id = v2.p_id and v1.user_id <> :user_id
RIGHT JOIN users as p on p.id = v1.user_id
INNER JOIN uf on uf.friend_id = p.id and uf.user_id = :user_id and is_active = true
INNER JOIN up on up.user_id = p.id and is_active = true
GROUP BY p.id, up.id
ORDER BY res desc";
$params = array(':user_id' => $user_id);
$aArrayOfRows = Yii::app()->db->createCommand($sql)->queryAll(true, $params);

How do i sort by users with profile pictures at the top?

So i'm filling in for our developer at the moment (be for-warned i'm a beginner) but I"m trying to simply sort my search results by profiles that have a profile picture included (i.e, i don't want blank profile pictures to show up at the top of the results...they should all be at the end of the results)...Note that there are a couple user types which is why there is so much code...
I'm pretty sure where i'm going wrong is the 2 lines...
ORDER BY $order u.picture ISNULL DESC"; (which relates to ordering by profile pictures). Would really appreciate any and all help...thx!
The code is as follows:
if ($user_type == 1) {
$sql = "SELECT a.*, u.*,
(SELECT COUNT(DISTINCT userId) FROM LF_usertype_A WHERE usertype_BId = u.userId AND status = 1) as i_cnt,
(SELECT COUNT(productId) FROM LF_products WHERE userId = u.userId AND status = 1) as product_cnt,
(SELECT COUNT(transactionId)
FROM LF_Transactions
WHERE usertypeBId = u.userId
AND (status = 1 OR status = 2)
AND type = 9
AND userId != usertypeBId
AND userId != usertypeAId) AS cnt
FROM LF_Users u
JOIN LF_products a ON a.userId = u.userId
LEFT JOIN LF_Transactions t ON t.productId = a.productId
WHERE a.status = 1
AND u.status = 1
AND u.userType = :ut $where
GROUP BY u.userID
ORDER BY $order u.name DESC LIMIT 200";
} elseif ($filter != "recent" && $user_type == 2) {
$sql = "SELECT u.*,
(SELECT COUNT(a.productId) FROM LF_usertypeA a INNER JOIN LF_products ON a.productId = m.productId INNER JOIN LF_Users uu ON uu.userId = a.usertypeAId WHERE a.userId = u.userId AND uu.status = 1 AND a.status = 1 AND m.status = 1) as product_cnt,
(SELECT COUNT(transactionId)
FROM LF_Transactions
WHERE usertypeBId = u.userId
AND (status = 1 OR status = 2)
AND type = 9
AND userId != usertypeAId
AND userId != usertypeBId) AS cnt
FROM LF_Users u
LEFT JOIN LF_Transactions t ON t.usertypeBId = u.userId
WHERE u.status = 1
AND u.userId != 1
AND u.userType = :ut $where
GROUP BY u.userID
ORDER BY $order u.name DESC LIMIT 200
ORDER BY $order u.picture ISNULL DESC";
} else {
$sql = "SELECT u.*,
(SELECT COUNT(a.productId) FROM LF_usertype_A a INNER JOIN LF_products m ON a.productId = m.productId INNER JOIN LF_Users uu ON uu.userId = a.usertypeAId WHERE a.userId = u.userId AND uu.status = 1 AND a.status = 1 AND m.status = 1) as product_cnt,
(SELECT COUNT(transactionId)
FROM LF_Transactions
WHERE usertypeBId = u.userId
AND (status = 1 OR status = 2)
AND type = 9
AND userId != usertypeAId
AND userId != usertypeBId) AS cnt
FROM LF_Users u
WHERE u.status = 1
AND u.userId != 1
AND u.userType = :ut $where
GROUP BY u.userID
ORDER BY $order u.name DESC LIMIT 200
ORDER BY $order u.picture ISNULL DESC";
}
You would have to put the isnull condition before your regular sort order if you want it to take precedence:
ORDER BY ISNULL(u.picture), $order

Categories