Display best selling items and associated image from another table - php

I would like to display the image of 4 best selling items on the index page but the sql I'm using does not work. I think the syntax is correct but doesn't show anything on the page. I have an order_items table and products table.
Products table
CREATE TABLE IF NOT EXISTS `products` (
`id` int(11) NOT NULL,
`date` datetime NOT NULL,
`category` int(11) NOT NULL,
`name` varchar(100) NOT NULL,
`image` varchar(100) CHARACTER SET utf8 NOT NULL,
`description` text NOT NULL,
`author` varchar(100) NOT NULL,
`price` decimal(5,2) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=27 ;
Order_items table
CREATE TABLE IF NOT EXISTS `order_items` (
`id` int(11) NOT NULL,
`order` int(11) NOT NULL,
`product` int(11) NOT NULL,
`price` decimal(8,2) NOT NULL,
`qty` int(11) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=68 ;
NOTE: in order_items table the field product corresponds to the ID of the product.
Finally, this is the sql statement I'm using but doesn't show anything.
public function bestSellingItems(){
$sql = "SELECT * FROM products AS p
INNER JOIN order_items AS od ON p.id = od.id
GROUP BY p.id, SELECT SUM(od.qty) AS total
ORDER BY SUM(od.qty) DESC limit 4";
}
I would appreciate any help.

You said it your self, product correspond to id and you used p.id = od.id , also, I didn't understand the part of the second select which I believe should throw an error(no from..) so I adjusted it a little bit - select the sum, alias it and order by that alias.
public function bestSellingItems(){
$sql = "SELECT p.*,od.*,sum(od.qty) as sum_qty FROM products AS p
INNER JOIN order_items AS od ON p.id = od.product
GROUP BY p.id
ORDER BY sum_qty DESC limit 4";
}

your join "INNER JOIN order_items AS od ON p.id = od.id " should be INNER JOIN order_items AS od ON p.id = od.Product

Related

MYSQL Join to get data in specific format

I've recently changed updated my database with a couple of new tables and having trouble to get(select) data from three different tables.
There are 4 stores which exchange stock with each other, it gets recorded in database.
Table 'sites' has store id and name info.
CREATE TABLE `sites` (
`id` int(10) NOT NULL,
`name` varchar(35) NOT NULL
)
Table 'stock_exchange_new' has info about stock transfer date, from
store, to store etc.
CREATE TABLE `stock_exchange_new` (
`id` int(11) NOT NULL,
`transfer_date` date NOT NULL,
`from_site` int(11) NOT NULL,
`to_site` int(11) NOT NULL,
`transfer_ref` varchar(255) NOT NULL,
`note` varchar(300) NOT NULL,
`added_by` int(11) NOT NULL,
`added_at` datetime NOT NULL,
`edited_by` int(11) NOT NULL,
`edited_at` datetime NOT NULL
)
Table 'stock_item_txns' has the information about what item was
exchanged/transferred:
CREATE TABLE `stock_item_txns` (
`id` int(11) NOT NULL,
`stock_exchange_id` int(11) NOT NULL,
`item_id` int(11) NOT NULL,
`units_per_ctn` int(11) NOT NULL,
`qty` decimal(10,2) NOT NULL,
`ctn_price` decimal(10,2) NOT NULL,
`total_price` decimal(10,2) NOT NULL
)
Now, for one particular store, I need the data shown as compare to itself, eg: for Store 1, it should be something like this:
Store Name Total_Sent Total_Received
Store2 500 200
Store3 490 580
Store4 300 400
Tried so far...
SELECT GREATEST(s1.name, s2.name) AS from_store,
LEAST(s1.name, s2.name) AS to_store,
SUM(CASE WHEN s1.name < s2.name THEN si.total_price ELSE 0 END) AS received,
SUM(CASE WHEN s1.name > s2.name THEN si.total_price ELSE 0 END) AS sent
FROM stock_exchange_new se
INNER JOIN sites s1
ON se.from_site = s1.id
INNER JOIN sites s2
ON se.to_site = s2.id
INNER JOIN stock_item_txns si
ON se.id = si.stock_exchange_id
GROUP BY GREATEST(se.from_site, se.to_site),
LEAST(se.from_site, se.to_site)
HAVING MAX(GREATEST(se.from_site, se.to_site)) = '1'
Here's the fiddle, for better understanding.
Utilising a couple of sub queries, something like this (not tested):-
SELECT s2.name AS 'Store Name',
from_site_total,
to_site_total
FROM sites s1
CROSS JOIN sites s2
LEFT OUTER JOIN
(
SELECT from_site,
to_site,
SUM(stock_item_txns.total_price) AS from_site_total
FROM stock_exchange_new
INNER JOIN stock_item_txns ON stock_exchange_new.id = stock_item_txns.stock_exchange_id
GROUP BY from_site,
to_site
) sub_from_site
ON s1.id = sub_from_site.from_site
AND s2.id = sub_from_site.to_site
LEFT OUTER JOIN
(
SELECT to_site,
from_site,
SUM(stock_item_txns.total_price) AS to_site_total
FROM stock_exchange_new
INNER JOIN stock_item_txns ON stock_exchange_new.id = stock_item_txns.stock_exchange_id
GROUP BY to_site,
from_site
) sub_to_site
ON s1.id = sub_to_site.to_site
AND s2.id = sub_to_site.from_site
WHERE s1.name = 'Store1'
AND s2.name != 'Store1'

Reduce time of MySQL JOIN statement execution

I have a notifcation system like in Facebook using the following MySQL statement:
SELECT
n.`id`,n.`content_id`,n.`site_id`,n.`creator_uid`,n.`type`,
nu.`id` AS nuid, nu.`uid` AS nu_uid, nu.`date`,
nr.`id` AS nrid, nr.`uid` AS nr_uid, nr.`is_read`,
u.`gender`
FROM `notification` AS n
LEFT JOIN `notification_user` AS nu ON nu.`nid` = n.`id`
LEFT JOIN `notification_read` AS nr ON nr.`nid` = n.`id`
LEFT JOIN `users` AS u ON u.`id` = nu.`uid`
WHERE
nu.`uid` != '".$_SESSION['uid']."' AND nr.`uid` = '".$_SESSION['uid']."'
OR
(
nu.`uid` = '".$_SESSION['uid']."' AND n.`type` = 'credits'
)
ORDER BY date DESC, nu.`id` DESC
It should only display the notifications for this specific user I'm logged in as. But now I've more than 22500 records on the notification table and I'm always getting an "maximum execution time exceeded" error.
Can I change this query somehow to reduce the time getting the wanted records? Maybe remove the join and execute more queries?
EDIT: Added Table Overview
CREATE TABLE IF NOT EXISTS `notification` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`content_id` int(11) NOT NULL,
`site_id` int(11) NOT NULL,
`creator_uid` int(11) NOT NULL,
`type` varchar(30) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=22759 ;
.
CREATE TABLE IF NOT EXISTS `notification_read` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`nid` int(11) NOT NULL,
`uid` int(11) NOT NULL,
`is_read` tinyint(4) NOT NULL,
PRIMARY KEY (`id`),
KEY `nid` (`nid`),
KEY `nid_2` (`nid`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=45342 ;
.
CREATE TABLE IF NOT EXISTS `notification_user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`nid` int(11) NOT NULL,
`uid` int(11) NOT NULL,
`date` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=22813 ;
Splitting the statement up in to a pair of SELECTs, and UNIONing the results together:-
(SELECT
n.`id`,n.`content_id`,n.`site_id`,n.`creator_uid`,n.`type`,
nu.`id` AS nuid, nu.`uid` AS nu_uid, nu.`date`,
nr.`id` AS nrid, nr.`uid` AS nr_uid, nr.`is_read`,
u.`gender`
FROM `notification` AS n
INNER JOIN `notification_user` AS nu ON nu.`nid` = n.`id`
LEFT JOIN `notification_read` AS nr ON nr.`nid` = n.`id`
LEFT JOIN `users` AS u ON u.`id` = nu.`uid`
WHERE nu.`uid` = '".$_SESSION['uid']."' AND n.`type` = 'credits')
UNION
(SELECT
n.`id`,n.`content_id`,n.`site_id`,n.`creator_uid`,n.`type`,
nu.`id` AS nuid, nu.`uid` AS nu_uid, nu.`date`,
nr.`id` AS nrid, nr.`uid` AS nr_uid, nr.`is_read`,
u.`gender`
FROM `notification` AS n
LEFT JOIN `notification_user` AS nu ON nu.`nid` = n.`id`
INNER JOIN `notification_read` AS nr ON nr.`nid` = n.`id`
LEFT JOIN `users` AS u ON u.`id` = nu.`uid`
WHERE nu.`uid` != '".$_SESSION['uid']."' AND nr.`uid` = '".$_SESSION['uid']."')
ORDER BY date DESC, nu.`id` DESC
This should allow MySQL to use indexes effectively on each part of the query. The first part of the query requires a notification_user record so you can use an INNER JOIN there, while the 2nd requires a notification_read record so you can use an INNER JOIN there. Both of those should cut the number of rows to process.
Add an index on the uid field on the notification_user table
Add an index on the uid field on the notification_read table

inner join slow performance

I have a table offers that has over 100k rows so the below query is very slow (4sec - average).
SELECT cat1.id AS cat1id,
cat1.title_gr AS title,
cat1.order
FROM categories_groups_cat1 AS cat1
INNER JOIN
( SELECT categories_id, categories_groups_cat1_id FROM
categories_vs_groups
GROUP BY categories_groups_cat1_id ) AS vs
ON vs.categories_groups_cat1_id=cat1.id
INNER JOIN
( SELECT id, title_gr FROM
categories
GROUP BY title_gr ) AS cats
ON cats.id=vs.categories_id
INNER JOIN
( SELECT category_gr FROM
offers
GROUP BY category_gr ) AS offers
ON offers.category_gr=cats.title_gr
GROUP BY cat1.id
ORDER BY cat1.order ASC
table offers
`id` int(11) NOT NULL,
`title` text NOT NULL,
`description` text NOT NULL,
`image` text NOT NULL,
`price` float NOT NULL,
`start_price` float NOT NULL,
`brand` text NOT NULL
`category_gr` text NOT NULL
table categories_groups_cat1
`id` int(11) NOT NULL,
`order` int(11) NOT NULL,
`title_gr` text NOT NULL
table categories_vs_groups
`id` int(11) NOT NULL,
`categories_groups_cat1_id` int(11) NOT NULL,
`categories_id` int(11) NOT NULL
table categories
`id` int(11) NOT NULL,
`title_gr` char(255) NOT NULL
I try to choose from categories_groups_cat1 where offers exist, that's why I use the inner join. I don't know if it is completely correct. If there is another faster(performance) solution I would appreciate it
You should avoid sub-query that creates temp table. This will surely improve performance. Sub-queries that create temp table in memory kills performance, try to avoid as much as you can.
I have modified your code. There may small syntactic errors.
SELECT cat1.id AS cat1id,
cat1.title_gr AS title,
cat1.order
FROM categories_groups_cat1 AS cat1
INNER JOIN
categories_groups_cat1_id AS vs
ON vs.categories_groups_cat1_id=cat1.id
INNER JOIN
categories
AS cats
ON cats.id=vs.categories_id
INNER JOIN
offers
ON offers.category_gr=cats.title_gr
GROUP BY cat1.id,cats.title_gr, offers.category_gr
ORDER BY cat1.order ASC

Users ranking table on how many likes/upvotes users had

I'm trying to create a ranking table based on how many likes/upvotes a user had on all his items in total. User in the upvotes table links to id of the user that made the like, but I think you don't need this.
Hopefully by giving these tables everything will get clear.
I think the trick here is to get all the upvotes by each item and merge them together towards a user this item was from to get a total likes for each user and then rank all the users based on this total. Of course doing this will probably be a slow query so I need a very performant way to handle this.
The hard thing is here mainly that the upvotes table doesn't include the user id.
3 tables:
CREATE TABLE `items` (
`id` int(255) NOT NULL AUTO_INCREMENT,
`user_id` int(255) NOT NULL,
`img` varchar(500) NOT NULL,
`message` varchar(200) NOT NULL,
`created_on` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`active` int(11) NOT NULL DEFAULT '1',
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=19 DEFAULT CHARSET=latin1;
CREATE TABLE `upvotes` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user` int(255) NOT NULL,
`item_id` int(255) NOT NULL,
`created_on` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=4 DEFAULT CHARSET=latin1;
CREATE TABLE `users` (
`id` int(255) NOT NULL AUTO_INCREMENT,
`email` varchar(255) NOT NULL,
`password` binary(60) NOT NULL,
`first_name` varchar(255) NOT NULL,
`last_name` varchar(255) NOT NULL,
`active` int(1) NOT NULL DEFAULT '1',
`created_on` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `email` (`email`)
) ENGINE=MyISAM AUTO_INCREMENT=17 DEFAULT CHARSET=latin1;
I need a performant query giving me the ranking of each user ranked on how many likes they got on all their items?
I managed to write this:
SELECT #rank := #rank + 1 AS rank, m.*
FROM (SELECT
users.first_name as first_name,
users.last_name as last_name,
count(upvotes.item_id) as total
FROM upvotes
INNER JOIN users
ON users.id = (SELECT items.user_id FROM items WHERE items.id = upvotes.item_id LIMIT 1)
GROUP BY users.id
ORDER BY total DESC
) m, (SELECT #rank := 0) r
But I reckon this will be super slow when the database grows...
You can do a simple join query in order to get the total likes for each item of user and order your results with the resulting count in descending order
SELECT u.*,i.*,COUNT(DISTINCT up.user) `total_user_likes_item`
FROM users u
JOIN items i ON(i.user_id = u.id)
JOIN upvotes up ON(up.item_id = i.id)
GROUP BY u.id,i.id
ORDER BY u.id,i.id,total_user_likes_item DESC
Edit from comments For user total likes you remove i.id from group by as below query
SELECT u.*,COUNT(DISTINCT up.user) `total_user_likes_item`
FROM users u
JOIN items i ON(i.user_id = u.id)
JOIN upvotes up ON(up.item_id = i.id)
GROUP BY u.id
ORDER BY total_user_likes_item DESC
I'll try answer your question:
In table users you can add row sum_upvotes. Every time when someone get one like (vote) you will increment this column by:
UPDATE users
SET sum_upvotes = sum_upvotes + 1
;
Of course, you will insert a column in table upvotes.
Finally, you query to select users and order them by upvotes will look like this
SELECT first_name, last_name
FROM users
ORDER BY sum_upvotes
;
Hope this helps.

Mysql product filters with multiple options

for example I have a list o TVs, and each TV has some attributes like: Brand(Samsung,Sony etc..), Size(80cm, 116 cm etc), SmartTv(yes, no).
I have the following schema:
CREATE TABLE `products` (
`id` int(11) NOT NULL auto_increment,
`name` varchar(150) NOT NULL,
)
CREATE TABLE `attributes` (
`id` int(11) NOT NULL auto_increment,
`name` varchar(20) character set latin1 NOT NULL
)
CREATE TABLE `attributes_entity` (
`product_id` int(11) NOT NULL,
`attribute_id` int(11) NOT NULL,
`value_id` int(11) NOT NULL,
)
CREATE TABLE `attributes_values` (
`id` int(11) NOT NULL auto_increment,
`value` varchar(255) default NULL,
)
If i want all TV from samsung i say like this:
SELECT
`p`.`id`,
`p`.`name`
FROM `attributes_entity` `ae`
INNER JOIN `products` `p` ON `ae`.`product_id`=`p`.`id`
INNER JOIN `attributes` `a` ON `ae`.`attribute_id`=`a`.`id`
INNER JOIN `attributes_values` `av` ON `ae`.`value_id`=`av`.`id`
WHERE (`a`.`name`='samsung' AND `av`.`value`='samsung')
This is great but what if I want: All Samsung TVs that are smartTv:
SELECT
`p`.`id`,
`p`.`name`
FROM `attributes_entity` `ae`
INNER JOIN `products` `p` ON `ae`.`product_id`=`p`.`id`
INNER JOIN `attributes` `a` ON `ae`.`attribute_id`=`a`.`id`
INNER JOIN `attributes_values` `av` ON `ae`.`value_id`=`av`.`id`
WHERE (`a`.`name`='samsung' AND `av`.`value`='samsung')
//imposible query
and (`a`.`name`='smartv' AND `av`.`value`='yes')
How should i fix the query with multiple ANDs?
First idea, off the top of my head - try replacing your joins with an inner query, and count the number of matching attributes:
SELECT `p`.`id`, `p`.`name`
FROM `products` `p`
WHERE `p`.`id` IN (SELECT `ae`.`product_id`
FROM `attributes_entity` `ae`
INNER JOIN `attributes` `a` ON `ae`.`attribute_id`=`a`.`id`
INNER JOIN `attributes_values` `av` ON `ae`.`value_id`=`av`.`id`
WHERE ((`a`.`name`='samsung' AND `av`.`value`='samsung') OR
(`a`.`name`='smartv' AND `av`.`value`='yes'))
HAVING COUNT(*) >= 2 -- number of matching attributes required
);

Categories