sql join not displaying correctly - php

I'm currently trying to join two tables with a left join:
--portal--
id_portal (index)
id_venue
name_portal
--access--
id_access (index)
id_event
id_portal
id_tickets
scan_access
'access' contains a number of ticket types per portal for each event. I need to combine these to get the sum total of the scan_access column for each portal but include the portals that have 'null' scan_access to come up with '0'. To achieve this I've used a left join:
SELECT portal.name_portal, SUM(access.scan_access) AS total_scan
FROM portal LEFT JOIN access ON portal.id_portal = access.id_portal
WHERE portal.id_venue = $venueId
GROUP BY portal.id_portal
ORDER BY portal.id_portal ASC
which means I get the following:
Portal 1 - Null
Portal 2 - 40
Portal 3 - 33
Portal 4 - Null
but I have an issue when I need to also get the above result when taking into account the event (id_event) because when I use the following:
SELECT portal.name_portal, SUM(access.scan_access) AS total_scan
FROM portal LEFT JOIN access ON portal.id_portal = access.id_portal
WHERE portal.id_venue = $venueId AND access.id_event = 20
GROUP BY portal.id_portal
ORDER BY portal.id_portal ASC
I get:
Portal 2 - 40
Portal 3 - 33
which makes sense as those are the only two rows that have an id_event value. But how can I take this col into account without losing the other portals? also, is there a way in sql to make the 'null' a zero when returning a result? (I can fix the null after with php but wanted to see if it was possible)

By putting access.id_event = 20 in your WHERE clause, you turn your LEFT JOIN into an INNER JOIN. Move access.id_event = 20 into your join criteria to preserve your LEFT JOIN. As #echo_me mentioned, you can use COALESCE() to get rid of your zeroes. I'd put it around the SUM(), instead of inside.
SELECT portal.name_portal, COALESCE( SUM(access.scan_access), 0 ) AS total_scan
FROM portal LEFT JOIN access ON portal.id_portal = access.id_portal AND access.id_event = 20
WHERE portal.id_venue = $venueId
GROUP BY portal.id_portal
ORDER BY portal.id_portal ASC

to convert NULL to 0 use this
COALESCE(col, 0)
in your example it will be
SUM(COALESCE(access.scan_access, 0)) AS total_scan

Related

Get data from two tables

I have a query regarding join . Basically there are two tables product and product_boost . The table product_boost has the product_id as foreign key which is also in product table .
I want to get the data using join which is available in both the tables, and if not only data from first table will come.
I am using right outer join, here is my query
SELECT * FROM `vefinder_product`
RIGHT OUTER JOIN `vefinder_product_boost` ON `vefinder_product_boost`.`product_id`=`vefinder_product`.`product_id`
WHERE `vefinder_product`.`status` = 1
AND `vefinder_product`.`post_type` != 5
AND `vefinder_product`.`country` IN('348')
AND `vefinder_product`.`product_stock` >0
AND `vefinder_product`.`product_in_stock` = 1
AND `vefinder_product_boost`.`target_age_from` >= 20
AND `vefinder_product_boost`.`target_age_to` <= 40
ORDER BY `vefinder_product`.`is_boosted` DESC,
`vefinder_product`.`is_sponsered` DESC,
`vefinder_product`.`created_date` DESC LIMIT 21
How can i achive the desired thing , because this is not working. I am using codeigniter php.
Use Left join instead, if you want to get all the data from first (leftmost) table.
Any Where conditions on tables other than the first table (leftmost), should be shifted to ON condition in Left Join. Otherwise, Where would filter out unmatched rows also (null in the right side tables).
Try the following instead:
SELECT *
FROM `vefinder_product`
LEFT OUTER JOIN `vefinder_product_boost`
ON `vefinder_product_boost`.`product_id`=`vefinder_product`.`product_id` AND
`vefinder_product_boost`.`target_age_from` >= 20 AND
`vefinder_product_boost`.`target_age_to` <= 40
WHERE `vefinder_product`.`status` = 1 AND
`vefinder_product`.`post_type` != 5 AND
`vefinder_product`.`country` IN('348') AND
`vefinder_product`.`product_stock` >0 AND
`vefinder_product`.`product_in_stock` = 1
ORDER BY `vefinder_product`.`is_boosted` DESC,
`vefinder_product`.`is_sponsered` DESC,
`vefinder_product`.`created_date` DESC
LIMIT 21
Use left join and put where condition in ON cluase
SELECT * FROM `vefinder_product`
left OUTER JOIN `vefinder_product_boost` ON `vefinder_product_boost`.`product_id`=`vefinder_product`.`product_id`
and `vefinder_product`.`status` = 1
AND `vefinder_product`.`post_type` != 5
AND `vefinder_product`.`country` IN('348')
AND `vefinder_product`.`product_stock` >0
AND `vefinder_product`.`product_in_stock` = 1
AND `vefinder_product_boost`.`target_age_from` >= 20
AND `vefinder_product_boost`.`target_age_to` <= 40
ORDER BY `vefinder_product`.`is_boosted` DESC,
`vefinder_product`.`is_sponsered` DESC,
`vefinder_product`.`created_date` DESC LIMIT 21
you can use third party software like SQLyog.
it is very simple for join query just build query with UI and assign relation to that fields between tables.
in sqlyog you can get data from multiple tables not only two tables.
because i am currently using this software for time saving.

Efficient comment system pagination query

So I've been looking around the web about any information about pagination.
From what I've seen there are 3 kinds, (LIMIT, OFFSET) a, (WHERE id > :num ORDER BY id LIMIT 10) b and (cursor pagination) c like those used on facebook and twitter.
I decided that for my project I'll go with the "b" option as it looks pretty straightforward and efficient.
I'm trying to create some kind of "facebook" like post and comment system, but not as complex.
I have a ranking system for the posts and comments and top 2 comments for each post that are fetched with the post.
The rest of the comments for each specific post are being fetched when people click on to see more comments.
This is a query for post comments:
SELECT
c.commentID,
c.externalPostID,
c.numOfLikes,
c.createdAt,
c.customerID,
c.numOfComments,
(CASE WHEN cl.customerID IS NULL THEN false ELSE true END) isLiked,
cc.text,
cu.reputation,
cu.firstName,
cu.lastName,
c.ranking
FROM
(SELECT *
FROM Comments
WHERE Comments.externalPostID = :externalPostID) c
LEFT JOIN CommentLikes cl ON cl.commentID = c.commentID AND cl.customerID = :customerID
INNER JOIN CommentContent cc ON cc.commentTextID = c.commentID
INNER JOIN Customers cu ON cu.customerID = c.customerID
ORDER BY c.weight DESC, c.createdAt ASC LIMIT 10 OFFSET 2
offset 2 is because there were 2 comments being fetched earlier as top 2 comments.
I'm looking for a way similar to this of seeking next 10 comments each time through the DB without going through all the rows like with LIMIT,OFFSET
The problem is that I have two columns that are sorting the results and I won't allow me to use this method:
SELECT * FROM Comments WHERE id > :lastId LIMIT :limit;
HUGE thanks for the helpers !
Solution So Far:
In order to to have an efficient pagination we need to have a single column with as much as possible unique values that make a sequence to help us sort the data and paginate through.
My example uses two columns to sort the data so it makes a problem.
What I did is combine time(asc sorting order) and weight of the comment(desc sorting order), weight is a total of how much that comment is being engaged by users.
I achieved it by getting the pure int number out of the DateTime format and dividing the number by the weight let's call the result,"ranking" .
this way a comment with a weight will always have a lower ranking ,than a comment without a weight.
DateTime after stripping is a 14 digit int ,so it shouldn't make a problem dividing it by another number.
So now we have one column that sorts the comments in a way that comments with engagement will be at the top and after that will come the older comments ,so on until the newly posted comments at the end.
Now we can use this high performance pagination method that scales well:
SELECT * FROM Comments WHERE ranking > :lastRanking ORDER BY ASC LIMIT :limit;
Ok i want to say about other way, in my opinion this very useful.
$rowCount = 10; //this is count of row that is fetched every time
$page = 1; //this is for calculating offset . you must increase only this value every time
$offset = ($page - 1) * $rowCount; //offset
SELECT
c.commentID,
c.externalPostID,
c.numOfLikes,
c.createdAt,
c.customerID,
c.numOfComments,
(CASE WHEN cl.customerID IS NULL THEN false ELSE true END) isLiked,
cc.text,
cu.reputation,
cu.firstName,
cu.lastName,
c.ranking
FROM
(SELECT *
FROM Comments
WHERE Comments.externalPostID = :externalPostID) c
LEFT JOIN CommentLikes cl ON cl.commentID = c.commentID AND cl.customerID = :customerID
INNER JOIN CommentContent cc ON cc.commentTextID = c.commentID
INNER JOIN Customers cu ON cu.customerID = c.customerID
ORDER BY c.ranking DESC, c.createdAt ASC LIMIT $rowCount OFFSET $offset
There can be an error because i didn't check it , please don't make it matter

SQL - Get AVG value from other table

My question sounds really easy, but I'm stuck.
Sample Data:
Listing:
id title State
1 Hotel with nice view Arizona
2 Hotel to stay Arizona
Review:
id listing_id rating mail_approved
1 1 4(stars) 1
2 1 4(stars) 0
3 1 3(stars) 1
4 2 5(stars) 1
So now I get the AVG value of the listings, but I want to get only the value of each listing when the review is mail_approved = 1. But when there is none review or no review with mail_approved = 1 it should give me the listing back just with 0.0 review points. So I would like to get all listing back if they have a review just calculate the AVG of those reviews with mail_approved = 1
How can I do this?
Do I have to rewrite the whole query?
Here is my query:
SELECT
ls.id,
title,
state,
ROUND(AVG(rating),2) avg_rating
FROM listing ls
JOIN review rv
ON ls.id = rv.listing_id
WHERE ls.state = '$get_state'
GROUP BY ls.id,
title,
state
ORDER BY avg_rating DESC
You used join, which is short for inner join. This type of join only gives results if a matching record exists in both tables. Change it to left join (short for left outer join), to also include listings without reviews.
You will need to move the state check and any other check to the join condition too, otherwise those listings without review will be dropped from the result again.
Lastly, you can coalesce the average value to get 0 instead of null for those records.
SELECT
ls.id,
title,
state,
COALESCE(ROUND(AVG(rating),2), 0) avg_rating
FROM listing ls
LEFT JOIN review rv
ON ls.id = rv.listing_id
AND ls.state = '$get_state'
AND ls.mail_approved = 1
GROUP BY ls.id,
title,
state
ORDER BY avg_rating DESC
As a side note, please check prepared statements (for PDO or MySQLi) for the proper way to pass input parameters to your query instead of concatenating with variables like $get_state. Concatting is error prone, and makes you more vulnerable for SQL injection.
Outer join the avarage ratings to the hotels:
select
l.id,
l.title,
l.state,
coalesce(r.avg_rating, 0)
from listing l
left join
(
select
listing_id,
round(avg(rating), 2) as avg_rating
from review
where mail_approved = 1
group by listing_id
) r on r.listing_id = l.id
where l.state = '$get_state'
order by avg_rating desc;

MySQL #1241 - Operand should contain 1 column(s) on counting

I am running this query, and I am getting ** #1241 - Operand should contain 1 column(s)** error:
SELECT `forumCategories`.`id`, `forumCategories`.`name`, `forumCategories`.`order`, `forumCategories`.`description`, `forumCategories`.`date_created`, COUNT(forumPosts.forumCategory_id) as postCount,
(SELECT `forumPosts`.*, `forumChildPosts`.`id`, `forumChildPosts`.`forumPost_id`, COUNT(forumChildPosts.forumPost_id) as childCount FROM `forumChildPosts` LEFT JOIN `forumPosts` ON `forumPosts`.`id` = `forumChildPosts`.`forumPost_id` GROUP BY `forumPosts`.`id`) AS childCount
FROM `forumCategories`
LEFT JOIN `forumPosts` ON `forumCategories`.`id` = `forumPosts`.`forumCategory_id`
GROUP BY `forumCategories`.`id`
ORDER BY `forumCategories`.`order` DESC
I have 3 tables:
forumCategories
forumPosts | forumPosts.forumCategory_id = forumCategories.id
forumChildPosts | forumChildPosts.forumPosts_id = forumPosts.id
I want to count all posts for the forum category, and them I want to count all the child posts that belongs to that forum category. How can I do this?
You can't select several items with a subselect and then give them one name. Now you're getting everything from forumPosts, something from forumChildPosts etc and trying to put that into a single column, childCount. This is not allowed.
It might be enough to remove all other result columns from that select and only leave the count?
I couldn't try it, is that makes sense ? But you can't get nested results from mysql due to its limitation, MYSQL is a Matrix table.
SELECT `forumCategories`.`id`,
`forumCategories`.`name`,
`forumCategories`.`order`,
`forumCategories`.`description`,
`forumCategories`.`date_created`,
COUNT(forumPosts.forumCategory_id) AS postCount,
(SELECT COUNT(forumChildPosts.forumPost_id) AS childCount FROM `forumChildPosts` LEFT JOIN `forumPosts` ON `forumPosts`.`id` = `forumChildPosts`.`forumPost_id` GROUP BY `forumPosts`.`id`) AS childCount
FROM `forumCategories`
LEFT JOIN `forumPosts` ON `forumCategories`.`id` = `forumPosts`.`forumCategory_id`
GROUP BY `forumCategories`.`id`
ORDER BY `forumCategories`.`order` DESC

mysql Query Optimization with inner join

I have a query
$query = "SELECT DISTINCT report_date,weekreportDate FROM contract_sales a
INNER JOIN contract b ON a.contract_UUID = b.UUID
INNER JOIN geoPoint c ON b.customer_UUID = c.customerUUID
WHERE c.com_UUID = '$com' AND a.report_date >= Date('$dateafter')
AND c.city_UUID = '$cit' ORDER BY `report_date`";
What I need to do is first get rid of all the results via date filtering but as you can see I get everything and then do my date sorting in the checks..
I am inner join all of them - is there a better way to do this?
I have a report for each date - and have two years of data - I want to get only dates in 2014 so as you can see I have 700+ dates that are useless to me right away but I have to go through all of them can check the other string UUID as well... what can I do to speed up my (working - albeit slow implementation)?
Explain information as requested:
Generation Time: Feb 20, 2014 at 06:48 PM
Generated by: phpMyAdmin 3.3.10.4 / MySQL 5.1.53-log
SQL query: EXPLAIN SELECT DISTINCT report_date,weekreportDate FROM contract_sales a INNER JOIN contract b ON a.contract_UUID = '1234' INNER JOIN geoPoint c ON b.customer_UUID = '1234' WHERE c.com_UUID = '1234' AND a.report_date >= Date('2014-01-01') AND c.city_UUID = '1234' ORDER BY `report_date`;
Rows: 3
id select_type table type possible_keys key key_len ref rows Extra
1 SIMPLE a ref uuid_conlcs uuid_conlcs 110 const 1 Using where; Using temporary; Using filesort
1 SIMPLE b ref uuid_cust uuid_cust 110 const 1 Using where; Using index; Distinct
1 SIMPLE c ref uuid_gargp,uuid_citgp uuid_citgp 110 const 1 Using where; Distinct
First, a rewrite of your query. I would not suggest using aliases just a, b, c, but something closer to context of table "cs" for contract_sales, "con" for contract, and "gp" for geoPoint... especially easier in larger more complex queries.
Also, ALWAYS try to qualify your query with table.column (or alias.column) as the WeekReportDate is not clear, but it appears to be associated with your contract sales table.
As for indexes in this construct, I would have an index on (report_date, weekreportDate, contract_uuid). This way, its a covering index to handle the columns being retrieved, the where clause, order by, and the join to the contract table without having to go back to the raw data pages.
The contract table, I would have an index on ( UUID, customer_UUID), also to be a covering index for the join from contract sales, and also to support the join to the geoPoint table.
Finally, your geoPoint table, an index on ( customerUUID, com_uuid, city_uuid ) to also cover the join and your filtering criteria.
SELECT DISTINCT
cs.report_date,
cs.weekreportDate
FROM
contract_sales cs
INNER JOIN contract con
ON cs.contract_UUID = con.UUID
INNER JOIN geoPoint gp
ON con.customer_UUID = gp.customerUUID
AND gp.com_UUID = '$com'
AND gp.city_UUID = '$cit'
WHERE
cs.report_date >= Date('$dateafter')
ORDER BY
cs.report_date
Now that being said, and I don't know the makeup of your tables for volume, but if you are looking for stuff for a particular COM/City, I would suspect that records qualifying that would be a much smaller set than ALL COM/City for the date range in question. So, I would reverse the query as below hoping the smaller dataset might query faster, but you would have to obviously try both out.
SELECT DISTINCT
cs.report_date,
cs.weekreportDate
FROM
geoPoint gp
INNER JOIN contract con
ON gp.customerUUID = con.customer_UUID
JOIN contract_sales cs
ON con.UUID = cs.contract_UUID
AND cs.report_date >= Date('$dateafter')
WHERE
gp.com_UUID = '$com'
AND gp.city_UUID = '$cit'
ORDER BY
cs.report_date
Actually the geoPoint index should be on your WHERE criteria first, then the customer UUID for the join to the next table (com_uuid, city_uuid, customeruuid ). The contract_sales index on ( contract_UUID, report_date ), and the contract table index on (customer_UUID, UUID ) to match the flow of joins of this query.

Categories