Mysql query to retrieve single image from an array of images? - php

Table to store array of Images:
`products` and `products_photos`
`products` includes only `id` field
`products_photos` includes `product_id` and `filename`
Table values:
products
--------
id-6
id-7
products_photos
---------------
6 - filename1
6 - filename2
7 - filename3
In these two table id 6 includes 2 images but i need to fetch only one image from that. How to write a query for that in mysql or laravel.

If you want to get the latest (last added) image of the product then you can do the following way
NOTE : Instead of *, use the precise columns so that your query performs faster.
SELECT * FROM products_photos WHERE product_id = 6 ORDER BY products_photos.id DESC LIMIT 1;
If you want to get the first (old added) image of the product then you can do the following way
SELECT * FROM products_photos WHERE product_id = 6 ORDER BY products_photos.id ASC LIMIT 1;
Updated : Query to get the list of all the records group
SELECT MAX(id) as id, photo_name FROM products_photos GROUP BY photo_name
In case if you have more than one columns and want to get the latest record for that too then go for this
Eg. Considering that your having description column and want to get the MAX (latest) content than use MAX, if you need oldest use MIN
SELECT MAX(id) as id, photo_name, MAX(description) as description FROM products_photos GROUP BY photo_name

You can give limit to your query to get single result
SELECT * FROM products_photos WHERE product_id = 6 ORDER BY id LIMIT 1;
Which will give single image only for id = 6 product
For retrieve all data use group by
SELECT * FROM GemSellerPortal.products pr
LEFT JOIN GemSellerPortal.products_photos ph
ON ph.product_id = pr.id
GROUP BY pr.id

Related

How to get the last seven days data from mysql details in brief

Actually I have a table which name is posts and another table which name is newscount , in posts table there is four column id , title ,details, postingDate
and in newscount table there is three column which are id, postid, count ,
and in newscount table postid is the id of posts table id , I have saved data in posts table and also i have data in newscount table , for example - in posts table I have
id title details postingDate
1,title1,details1,somedate1
2,title2,details2,somedate2
3,title3,details3,somedate3
and in newscount table I have
id=1,postid=1,count=6
id=2,postid=2,count=5
id=3,postid=3,count=7
I want to select last two data from posts table which have maximum count , like if i select then it should show result like newscount.id=3,posts.id=3 which has max 7 count and newcount.id=1,posts.id=1 and its details
I have tried but it is showing only postsid 3detials not last two
SELECT * FROM (SELECT newscount.postId, newscount.count from newscount WHERE newscount.count = (SELECT max(count) FROM newscount ORDER BY id LIMIT 2) ) tempcounts INNER JOIN posts ON posts.id = tempcounts.postId WHERE posts.isActive=1 AND posts.postingDate >= curdate() - INTERVAL DAYOFWEEK(curdate())+6 DAY AND posts.postingDate < curdate() - INTERVAL DAYOFWEEK(curdate())-1 DAY ORDER BY posts.postingDate DESC limit 2
I couldn't run your query because you didn't give a complete table structure of your db, but you have at least 2 item to make them correct:
first:
you have this query, but it does not return two parameters(except in condition you have more than one row with max value)
(SELECT max(count) FROM newscount ORDER BY id LIMIT 2)
instead of that use this:
(SELECT count FROM newscount ORDER BY count DESC LIMIT 2)
the second: if you expect to get more than 1 row from a subquery in where clause you should use in instead of = operand

Select distinct column from table

I have the database structure as shown in the below image:
I want to retrieve variant_id that belongs to particular product_id
Example :
lets say 1 and Size = L , Color = Green.
I expect mysql query to return variant_id = 7.
What is the expected query to be used in this scenario?
You can use following query.
I'm assuming your table name is table1
select variant_id from (select * from table1 where
product_id=1 and ((attribute_name='Size' and value='L')
or (attribute_name='Color' and value='Green'))) as temp
group by variant_id having count(*)>1

Counting # of rows in table which contain file_name

I am trying to make a page which displays products added to a database.
I need to use 'foreach' to automatically display all products.
Im stuck with one part where I need to display the number of downloads of each product. The only way to do this is to count the number of rows which contain the file name of the product in the downloads table.
This is what I use so far, but its not working:
SELECT * FROM products, file_product, files, downloads WHERE products.id = file_product.product_id AND file_product.file_id = files.id AND files.file_name = downloads.file_name
These are my tables: [products, file_product, files, downloads]
It sounds to me like you're doing this the hard way. I might suggest you look at mysql's grouping functions, specifically GROUP BY. You won't have to loop over the query at all, just the results.
Something like
SELECT `file_name`, COUNT(*) AS `count` FROM `files` GROUP BY `file_name`;
The results should look something like this:
---------------------------
| file_name | count|
--------------------------|
| background-2.png | 2 |
| foo.png | 1 |
---------------------------
You can JOIN that with your file_product table if you need to limit it to only files for the current product, as what I wrote will give you all files for all products.
Example:
SELECT
f.`file_name`,
COUNT(*) AS `count`
FROM `files` f
JOIN `file_product` fp
ON fp.`file_id` = f.`id`
JOIN `product` p
ON fp.`product_id` = ?
JOIN `downloads` d
ON d.`file_name` = f.`file_name`
GROUP BY `file_name`;
? is where you put the product id for the current product.
You have to write :
SELECT `file_name'`, COUNT(*) AS `count` FROM table GROUP BY `count` ORDER BY `count` DESC;
Then, this command returns how many rows per table for each file_name group by descroissant order.
In order to implement whith PHP :
<?php
// connect to MySQL
$db = mysql_connect('localhost', 'login', 'password');
// select database
mysql_select_db('database_name',$db);
// SQL query
$sql = 'SELECT `file_name`, COUNT(*) AS `count` FROM table GROUP BY `count` ORDER BY `count` DESC;';
$req = mysql_query($sql) or die('Error SQL !<br>'.$sql.'<br>'.mysql_error());
// close mysql
mysql_close();
?>
I can't test it, so it's maybe false :/

SQL Table Structure for news site

I want to make a fast table structure for news site with php and mysql. My database structure is ID, title, content, cat_ids (; separedet IDs of categories - ;5;10;15;20;), active, publish_date.
I want to make a fast query to select news from this table. Something like that:
SELECT id
FROM news
WHERE cat_ids LIKE '%;15;%'
AND active = 1
AND publish_date < NOW()
ORDER by publish_date DESC
LIMIT 0, 10
But if my table is 2-3GB the query is very slow. I need some ideas to make structure and make the select faster.
Instead of using cat_ids column, try creating a news_cats table with news_id and cat_id, and using this query:
SELECT id
FROM news JOIN news_cats ON news_id = id
WHERE cat_id = 15
AND active = 1
AND publish_date < NOW()
ORDER by publish_date DESC
LIMIT 0, 10
Some suggestions as below:
1) Create index on "active" field
2) Create index on "publish_date" field
3) Create separate table for category and news relation and remove "cat_ids" field from news table
New table might look like below:
news_category_ids
news_id
category_id
It can have multiple rows for each news_id, if news item falls in 3 categories, it will have 3 rows
Then use SQL like below:
SELECT news.id
FROM news INNER JOIN news_category_ids ON news.id = news_category_ids.news_id
WHERE 1
AND news.active = 1
AND news_category_ids.cat_id = 15
AND news.publish_date < NOW()
ORDER by news.publish_date DESC
LIMIT 0, 10

How can I get the nearest rows in mysql?

Lets say I'm trying to build a thumbnail of some gallery (5 thumbnails showing). How can I get my mysql to display 5 thumbnails, the middle thumbnail will be the image blown up, and the two on the left of the middle will be previous images, and the two other images on the right of the middle will be 2 more images after.
EDIT
I know how to easily get 5 thumbnails with something like this
$sqlThumb = mysql_query("SELECT iID,thumbnails,userID FROM images WHERE userID = ".$_SESSION['userID']." ORDER BY iID ASC LIMIT 1,5");
But the thing is, I dont have a consistent id (meaning, there will be deleting and inserting). It is based on the images that the user has.
iID userID
----- --------
1 5
2 4
3 4
4 5
5 5
6 5
10 5
11 5
12 5
So if a user clicks an image which shoes iID number 5, the thumbnail should show like this in order, 1,4,5,6,10.
However, also if a user clicks on thumbnail number 10, the thumbnail should show: 5,6,10,11,12.
Try this
$offset = $current_id-3;
(SELECT * FROM TBL WHERE id < '$current_id' limit '$offset',2 )
union( SELECT * FROM TBL WHERE id = '$current_id')
union (SELECT * FROM TBL WHERE id > '$current_id' limit 2)
I don't know if this works, but the idea is to have an attribute called row_number. You will get the image you want by the id and the two last and the two next by the row number.
SELECT iID,thumbnail FROM image_collection,
(SELECT iID, thumbnail, row_number
FROM
(SELECT iID,thumbnail,
#curRow := #curRow + 1 AS row_number
FROM image
WHERE userID = 5
ORDER BY iID) as image_collection
WHERE s_image.iID = 10) as image_selected
WHERE image_collection.row_number BETWEEN image_selected.row_number - 2 AND image_selected.row_number + 2
I don't tested it because I don't have MySQL running, but I see how to put the row number here: With MySQL, how can I generate a column containing the record index in a table?
Try this one (doesn't include any subtraction):
$id = 5;
$user_id = $_SESSION['userID'];
$sqlThumb = mysql_query("
SELECT iID FROM images WHERE userID = ".$user_id." AND iID = ".$id."
UNION (SELECT iID FROM images WHERE userID = ".$user_id." AND iID < ".$id." ORDER BY iID DESC LIMIT 2)
UNION (SELECT iID FROM images WHERE userID = ".$user_id." AND iID > ".$id." ORDER BY iID ASC LIMIT 2)
ORDER BY iID ASC")

Categories