I'm loading comments for product with id = '3'
$get_comments = mysql_query("SELECT * FROM products_comments WHERE product_id = '3'");
Now I want to add the "report abuse" option for each comment, for this purpose I'm having another table as "abuse_reports" which user abuse reports will be stored in this table, now if a user reported a comment, the report abuse option should not be there for that comment for that user there anymore, for this I'm doing:
while($row = mysql_fetch_array($get_comments)){
echo blah blah blah // comment details
// now for checking if this user should be able to report this or not, i make this query again:
$check_report_status = mysql_query("SELECT COUNT(id) FROM abuse_reports WHERE reporter_user_id = '$this_user_id' AND product_id = 'this_product_id'");
// blah blah count the abuse reports which the current user made for this product
if($count == 0) echo "<a>report abuse</a>";
}
With the above code, for each comment I'm making a new query, and that's obviously wrong, how I should join the second query with the first one?
Thanks
Updated query (that is working now, commited by questioner)
SELECT pc. * , count( ar.`id` ) AS `abuse_count`
FROM `products_comments` pc
LEFT OUTER JOIN `abuse_reports` ar ON pc.`id` = ar.`section_details`
AND ar.`reporter_id` = '$user_id'
WHERE pc.`product_id` = '$product_id'
GROUP BY pc.`id`
LIMIT 0 , 30
The query works as follow: You select all the fields of your products_comments with the given product_id but you also count the entries of abuse_reports for the given product_id. Now you LEFT JOIN the abuse_reports, which means that you access that table and hang it on to the left (your products_comments table). The OUTER allows that there is no need for a value in the abuse_reports table, so if there is no report you get null, and therefore a count of 0.
Please read this:
However, I needed to group the results, otherwise you get only one merged row as result. So please extend your products_comments with a field comment_id of type int that is the primary key and has auto_increment.
UPDATE: abuse count
Now you can do two things: By looping through the results, you can see for each single element if it has been reported by that user or not (that way you can hide abuse report links for example). If you want the overall number of reports, you just increase a counter variable which you declare outside the loop. Like this:
$abuse_counter = 0;
while($row = mysql....)
{
$abuse_counter += intval($row['abuse_count']); // this is 1 or 0
// do whatever else with that result row
}
echo 'The amount of reports: '.$abuse_counter;
Just a primitive sample
I believe your looking for a query something like this.
SELECT pc.*, COUNT(ar.*)
FROM products_comments AS pc
LEFT JOIN abuse_reports AS ar ON reporter_user_id = pc.user_id AND ar.product_id = pc.product_id
WHERE product_id = '3'"
try this SQL
SELECT pc.*, COUNT(ar.id) AS abuse_count
FROM products_comments pc
LEFT JOIN abuse_reports ar ON pc.product_id = ar.product_id
WHERE pc.product_id = '3' AND ar.reporter_user_id = '$this_user_id'
GROUP BY pc.product_id
The result is list of products_comments with abuse_reports count if exist for reporter_user_id
Related
I try to get the records from opportunity that created manually, so it means it’s not created via Converted from Leads or other module.
I’m trying to do is to get the opportunity record that is not converted from leads.
Below, you will see my query using left join the leads to opportunity using
opportunity id from leads table and the opportunity id from Opportunity table.
But whenever I try to run this query it doesn’t show the records that created manually in the opportunity,
I just want to get the records that are not converted and created manually in the opportunities. May I know why it is not showing? Thanks guys.
$strQuery = " SELECT
*
FROM
leads l
LEFT JOIN
opportunities O
ON
l.opportunity_id = O.id
WHERE
l.deleted = '0'
AND
O.deleted = '0'
AND
l.converted = '0'
AND
DATE_FORMAT(O.date_created, '%y-%m-%d') = CURDATE()";
//
$hQuery = $db->query($strQuery);
//
while ( $arRow = $db->fetchByAssoc($hQuery) ){
// My logic
}
I just want to get the records that are not converted and created manually in the opportunities
You may need to reverse the table relationships, e.g.
SELECT *
FROM opportunities O
LEFT JOIN leads l ON O.id = l.opportunity_id
WHERE l.opportunity_id IS NULL
AND O.deleted = '0'
AND DATE_FORMAT(O.date_created, '%y-%m-%d') = CURDATE()
here there is no assocated "lead", just an "opportunity".
I have an SQL query that fetches posts from a database. Everything works fine, but now I need to order the results by the number of comments each post has. The comments are on a separate table and they have a post_id column that links it to the post. I need to order the posts by the count of the comments table based on a shard ID? I have tried everything but every time I try to add something to my query it stops running completely and leaves my page blank. I need help to know where to put the other JOIN statement. This is my query:
$union = "UNION ALL
(
SELECT DISTINCT wallposts.p_id,wallposts.is_profile_notes,wallposts.times_viewed,wallposts.columnTimesShared,
wallposts.marked,wallposts.secure_id,wallposts.reshared,wallposts.group_id,
wallposts.totaluploads,wallposts.WallUploadID,wallposts.type,
wallposts.value,wallposts.media,wallposts.youtube,wallposts.post_type,
wallposts.privacy,wallposts.tagedpersons,wallposts.with_friends_tagged,wallposts.emotion_head,wallposts.selected_emotion,wallposts.title,
wallposts.url,wallposts.description,wallposts.cur_image,
wallposts.uip,wallposts.likes,wallposts.userid,
wallposts.posted_by,wallposts.post as postdata,wallusers.*,
UNIX_TIMESTAMP() - wallposts.date_created AS TimeSpent,
PosterTable.mem_pic as posterPic, PosterTable.gender as posterGender,PosterTable.oauth_uid as poster_oauth_uid, PosterTable.username as posterUsername,
PosterTable.mem_fname as posterFname,PosterTable.work as posterWork,
PosterTable.mem_lname as posterLname,walllikes_track.id as PostLikeFound,wallposts.date_created
FROM
wallusers,wallusers as PosterTable, wallposts
LEFT JOIN walllikes_track
ON wallposts.p_id = walllikes_track.post_id AND walllikes_track.member_id = ".$user_id."
WHERE
wallusers.active = 1
AND
PosterTable.active = 1
AND
wallposts.group_id IN (".$groups.")
AND
wallposts.group_id != 0
AND
PosterTable.mem_id = wallposts.posted_by
AND
wallposts.marked < ".$this->flagNumber."
AND
wallusers.mem_id = wallposts.posted_by ) ";
The comments table is called wallcomments and it has a column called post_id. I know I need to use JOIN and COUNT but I don't know where to put it within my current code.
Try this query, I didn't run but i updated it.
SELECT wallposts.p_id,wallposts.is_profile_notes,wallposts.times_viewed,wallposts.columnTimesShared,
wallposts.marked,wallposts.secure_id,wallposts.reshared,wallposts.group_id,
wallposts.totaluploads,wallposts.WallUploadID,wallposts.type,
wallposts.value,wallposts.media,wallposts.youtube,wallposts.post_type,
wallposts.privacy,wallposts.tagedpersons,wallposts.with_friends_tagged,wallposts.emotion_head,wallposts.selected_emotion,wallposts.title,
wallposts.url,wallposts.description,wallposts.cur_image,
wallposts.uip,wallposts.likes,wallposts.userid,
wallposts.posted_by,wallposts.post as postdata,wallusers.*,
UNIX_TIMESTAMP() - wallposts.date_created AS TimeSpent,
PosterTable.mem_pic as posterPic, PosterTable.gender as posterGender,PosterTable.oauth_uid as poster_oauth_uid, PosterTable.username as posterUsername,
PosterTable.mem_fname as posterFname,PosterTable.work as posterWork,
PosterTable.mem_lname as posterLname,walllikes_track.id as PostLikeFound,wallposts.date_created
FROM
wallusers,wallusers as PosterTable, wallposts
WHERE
wallusers.active = 1
AND
PosterTable.active = 1
AND
wallposts.group_id IN (".$groups.")
AND
wallposts.group_id != 0
AND
PosterTable.mem_id = wallposts.posted_by
AND
wallposts.marked < ".$this->flagNumber."
AND
wallusers.mem_id = wallposts.posted_by ) " AND wallposts.p_id = walllikes_track.post_id AND walllikes_track.member_id = ".$user_id.";
A more readable query might look like this...
At least then we'd have a chance.
SELECT DISTINCT p.p_id
, p.is_profile_notes
, p.times_viewed
, p.columnTimesShared
, p.marked
, p.secure_id
, p.media...
FROM wallposts p...
My deepest apologies for the query, that's legacy code for you. I basically want to check my code makes logical sense.
Essentially I want to return all rows of the "signatures" table where the "claim_id" = the "claim_id" on the "claims" table.
From that, I intend to check if the "signature_id" = null for each claim. If it does, that claim has no related signature, correct?
$SQL="
SELECT
`claims`.`claim_id`,
CONCAT(`insurers`.`insurer_name`,IF((`insurers`.`insurer_branch`<>''),CONCAT(' - ',`insurers`.`insurer_branch`),'')) as 'insurer',
`claims`.`claim_number` as 'claim_number',
UNIX_TIMESTAMP(claims.overflow_date) as 'overflow_date',
UNIX_TIMESTAMP(claims.reassigned_date) as 'reassigned_date',
UNIX_TIMESTAMP(claims.reassigned_from_fr_date) as 'reassigned_from_fr_date',
UNIX_TIMESTAMP(claims.date_of_first_contact) as 'date_of_first_contact',
UNIX_TIMESTAMP(`claims`.`date_surveyor_made_contact`) as 'date_surveyor_made_contact',
UNIX_TIMESTAMP(`claims`.`date_of_inspection`) as 'date_of_inspection',
UNIX_TIMESTAMP(`claims`.`surveyor_completed`) as 'surveyor_completed',
UNIX_TIMESTAMP( CASE 1 WHEN (claims.overflow_date>0) THEN claims.overflow_date WHEN (claims.reassigned_date>0) THEN claims.reassigned_date WHEN (claims.reassigned_from_fr_date>0) THEN claims.reassigned_from_fr_date ELSE claims.date_of_first_contact END ) as 'date_of_first_contact_debug',
`claims`.`date_surveyor_made_contact` as 'date_surveyor_made_contact_debug',
`claims`.`date_of_inspection` as 'date_of_inspection_debug',
`claims`.`surveyor_completed` as 'surveyor_completed_debug',
`claims`.`letter_of_findings`,
`claims`.`int_settlement_reason`,
`claims`.`ext_settlement_reason`,
`claims`.`original_surveyor_id`,
`claims`.`surveyor_id`,
`claims`.`broker_name`,
`insurers`.`insurer_type`,
`insurers`.`insurer_id`,
`signatures`.`signature_id`,
`signatures`.`claim_id`
FROM
(((`claims` claims INNER JOIN `insurers` insurers ON claims.`insurer_id` = insurers.`insurer_id`)
INNER JOIN `users` users ON claims.surveyor_id = users.user_id)
LEFT JOIN `signatures` signatures on claims.claim_id = signatures.claim_id)
WHERE
(`claims`.`claim_type` <> ".$conn->qstr(TYPE_DESKTOP).") AND
(`claims`.`claim_type` <> ".$conn->qstr(TYPE_AUDIT).") AND
(`claims`.`insurer_id` NOT IN ('".implode("','",$arrSURGE)."')) AND
(`users`.`status` = ".$conn->qstr(STATUS_LIVE).") AND
(`claims`.`claim_cancelled_id` = 0) AND
$where
";
The code I've added is both the signatures. selectors, and the LEFT JOIN 'signatures' signatures on claims.claim_id = signatures.claim_id) line.
claim_id is PK on the claims table, and signature_id is PK on signatures table.
Thanks!
The null check will only shows items with signatures. If you leave the null check out of the picture, you will get nulls for items where signature is not present.
check this
Here is my code:
<?php
$data = mysql_query("SELECT * FROM board") or die(mysql_error());
while($info = mysql_fetch_assoc( $data ))
{
if(!empty($info['user'])){
Print "".$info['user'].""; }
else {
}
myOtherQuery($info['id']);
}
function myOtherQuery($id) {
$result3 = mysql_query("SELECT COUNT(source_user_id) FROM likes
INNER JOIN pins ON pins.id = likes.pin_id
WHERE pins.board_id='$id'");
$c = mysql_result($result3, 0); // Cumulative tally of likes for board
{
Print "$c";
}
}
?>
The first part gets a users name and board details (board as in a photo album).
the second part joins that data with another sql table that counts the number of likes that board has.
Both are displayed as a name and a score represented by a number.
By default they are ordered by the date of creation. I'd like to be able to order them by the score. However, since the score is determined in the second part of the code, I don't know how to achieve it. Is it possible?
The solution is of course to query both at once in the first place, via a LEFT JOIN against a subquery returning the count per board_id:
SELECT
board.*,
/* Your PHP code will retrieve the likes count via this alias `numlikes` as in $info['numlikes'] */
numlikes
FROM
board
LEFT JOIN (
/* Subquery returns count per board_id */
SELECT pins.board_id, COUNT(source_user_id) AS numlikes
FROM
likes
INNER JOIN pins ON pins.id = likes.pin_id
GROUP BY pins.board_id
) likes ON board.id = likes.board_id
ORDER BY numlikes
It is nearly always significantly more efficient to perform a single query rather than n queries in a loop. You should strive to do so whenever possible.
You can do it in one query
SELECT board.*, count(likes.source_user_id) as score
FROM board
INNER JOIN pins
ON pins.board_id = board.id
INNER JOIN likes
ON pins.id = likes.pin_id
ORDER BY score
Fiddle with tables here
I'm using the following sql with the tables in the fiddle to check if a user has reached the borrowing limit. The problem here is, If an invalid item number were supplied it returns NULL, if a user has not borrowed any items, it returns NULL. This way, I cannot tell if a invalid item number were supplied or if a user actually has not borrowed any books. What would be a good way to check if a invalid item number was supplied or a member actually has not borrowed anything under that category?
set #mId = 3 //Has not borrowed anything till now.
set #id = 21; //This item does not appear in the collection_db table and is therefore invalid.
set #country = 'US';
SELECT col1.id, col1.holder, col2.borrowMax maxLimit, count(lend.borrowedId) as `count`
FROM collection_db col1
INNER JOIN collection_db col2
ON col1.holder = col2.id
INNER JOIN lendings lend
ON col1.holder = lend.holder and col1.country = lend.country
WHERE col1.id = #id and col1.country = #country
AND col2.category = 10
AND lend.memId = #mId and lend.country = #country
The furthest I could get with the one query is (had to take out php and "country" vars for fiddle to work):
SELECT col1.id, col1.holder, col2.borrowMax maxLimit, count(lend.borrowedId) as `count`
,case when valid1.id is not null then 'true' else 'false' end as validId
FROM collection_db col1
INNER JOIN collection_db col2
ON col1.holder = col2.id
INNER JOIN lendings lend
ON col1.holder = lend.holder,(
Select Distinct a.id From collection_db a
Where a.id = 4) valid1
WHERE col1.id = 4
AND col2.category = 10
AND lend.memId = 1
You may have to do a preparatory query checking for a valid memId:
$theQuery = "SELECT DISTINCT memId FROM lendings WHERE memId = 1"
Then test it here:
if (mysql_num_rows(mysql_query($theQuery)) <= 0) { /* No memId exists */ }
else { /* Do big query here */ }
You can use a tableA LEFT JOIN tableB, which will return results for the tableA even if tableB has no matches and will return NULL values for those in tableB.
Unfortunately, I can't quite figure out where you need LEFT JOINS, but probably you want them in both places.
You also might have to reorder the tables if it is the first table that should be on the right side of a LEFT JOIN. You could use a RIGHT JOIN but it is less readable to me.
maybe you should try "left join" if col1 do not have too much data,or do the query step by step