Self inner join to get single record - mysql

I have an SQL table data as follow
I want to display single record for product
example
90792 Amlaan-Hi-Power .............. Show only 1 record when there are 2 record
90793 Amlaan-Neutral .............. show only 1 record when there are 2 record
90794 Amlaan-Phosphate free .........show only 1 record when there are 2 record
90801 Acetone .......................show only 1 record when there are 2 record
90901 Acetanilide ...................show only 1 record when there is 1 record
Can I do this using Inner join
I know
select distinct product from product ORDER BY `product`.`product` DESC
will select distinct (unique) product code and that to only one field i.e. product but confused how to get other information using SQL statement
but results in duplicate records or same table...........................

It looks like your duplicate rows vary by the quantity of product in the package.
You can display just the product and name with
SELECT DISTINCT product, name
FROM product
If you want to deal with the quantity as well, that's a little trickier. This might work: it will put all product codes on one line.
SELECT product,
GROUP_CONCAT(product_code ORDER BY product_code) product_codes,
name
FROM product
GROUP BY product, name
Self join doesn't make a whole lot of sense for this application.

Use group by option for such purposes.
SELECT product,GROUP_CONCAT(product_code SEPERATOR '|') AS product_code,name FROM Table GROUP BY NAME
It will show only one record for duplicate names.
The multiple enteries of product code will seperated by | .

Related

Using GROUP BY to get the entry with the highest value

I need to create a product list with a preview image for each product.
I have a pretty simple data structure for products. One table is for the products, and one table for the images of a product. A product can have any number of images. The structure looks like this:
PRODUCT
id | name
1 Test Product A
2 Test Product B
3 Test Product C
PRODUCTIMAGE
id | productId | file | priority
1 1 foo.jpg 0
2 1 bar.jpg 1
3 2 something.png 1
4 2 yada.png 0
5 1 yougettheidea.gif 2
Pretty straight forward. The only thing worth mentioning about this is that productimages have a "priority", which is a TINYINT to determine the display order of images for a given product. The idea is: The higher the priority, the earlier the image should be displayed in the list of product images on the detail page. But for this product list that we are about to create, I'm only gonna need one preview image per product.
So as stated initially, my goal is to get a list of all products. So let's start pretty simple:
SELECT *
FROM product
Now I also want to display one preview image in the product page, so I need a little join:
SELECT `p`.*,
`pi`.`file` `previewImage`
FROM `product` `p`
LEFT JOIN `productImage` `pi` ON (`pi`.`productId` = `p`.`id`)
GROUP BY `p`.`id`
So far so good, this gives me one preview image per product to display on the product list. Just one more step to go: I want the preview image with the highest priority for each product as the preview image. So I tried to use a subquery to get the product images in the desired priority order:
SELECT `p`.*,
`pi`.`file` `previewImage`
FROM `product` `p`
LEFT JOIN (
SELECT *
FROM `productImage`
ORDER BY `priority` DESC
) `pi` ON (`pi`.`productId` = `p`.`id`)
GROUP BY `p`.`id`
But for some reason this doesn't (reliably) get me the product image with the highest priority for each product. Why is that? I think that GROUP BY is selecting the wrong productImage entry to keep, but why? Shouldn't it pick the first one, which due to the subquery should be the one with the highest priority?
Your group by is a partial group by. You are grouping by product.id so MySQL will group the result per product, but within each group it is free to return any row from productimage table. To get deterministic results, each column from that table needs to be wrapped inside aggregate functions (MIN, MAX, etc) but that will not give you the image with highest priority.
That being said, if you want only one column from the productimage table you can use a subquery inside select:
select product.*, (
select file
from productimage
where productimage.productid = product.id
order by priority desc
limit 1 -- this is the important bit
) as productimage_file
from product

Get DISTINCT show.name and COUNT of associated seasons

I'm trying to write a SQL statement that outputs a table with the two columns show name and number of seasons. The show column must contain no duplocates and the number of seasons column counts the number of seasons associated with the show entity.
Here are my two tables
Shows Table
id | name
Seasons Table
id | show_id | season_number
Here's what I've tried so far
SELECT DISTINCT shows.name
FROM shows
INNER JOIN seasons on show.id = seasons.show_id;
The above code works for grabbing distinct names but whenever I try adding COUNT(season.id) it breaks.
Any suggestions?
Thanks!
Use group by to aggregate multiple rows with the same name into a group. With count(distinct id) you calculate the number of distinct values of the id column in that group.
SELECT name
, COUNT(DISTINCT seasons.id)
FROM shows
JOIN seasons
ON shows.show_id = seasons.show_id
GROUP BY
name
By the way, I'd expect a season to have a one to many relation to show, not the other way around.

Get the lastest entry for a certain item? Mysql

Lets say I have a table with 2 columns, 1 contains Cars and 1 contains random numbers.
How can I search for the lastest "ferrari" entry in the table and know whats the random number for that ferrari?
I assume your Cars table has columns id, name,rnid
You can use following sql;
SELECT MAX(c.id) AS latestferrari FROM Cars c INNER JOIN randomnumbers rn ON c.rnid=rn.id WHERE c.name="ferrari"

mysql select problem

Hi were trying to perform a mysql select which isnt going to plan and hoping someone can shed some light on it.
we have estimated 10,000 plus listing records, a customer can have several listing records for different locations. we need to select all customer listings where at least one of the locations is equal to a specifield location.
so for example lets say customer 1 has a listing in sheffiled, doncaster, leeds, wakefield and customer 2 has listings in london and brighton.
Now I want to select all customer listings where one of the listings is for the area sheffield.
Id hope to get back the 4 rows for customer 1 because one of his listings is in sheffield.
for the sake of this example lets just presume the table consists of just customerId and LocationName
I need to select all customerIds where one of the locationNames = sheffield. So Id get 4 rows retruend with the cusotmer ID and the 4 locations
How do you write this query in mysql? Im guessing subselect but not too sure.
SELECT customerid FROM customers_location
WHERE customerid IN(SELECT DISTINCT customerid FROM customers_location WHERE LocationName = 'sheffield')
Something like:
SELECT * FROM CUST_TABLE WHERE CUST_ID IN (
SELECT DISTINCT CUST_ID FROM CUST_TABLE WHERE CUST_LOCN='Sheffield')
Note; The distinct clause may not be strictly necessary, not sure.
That would give you eg. 4 records for customer xyz who has one of their listing locations as Sheffield, which I think is what you're asking.

Sql reports with BI Studio (BIDS) , I want one Entry per Page

Imagine I have 10 Categories. For each categories I have many Products.
Category
CategoryID(PK)
CategoryName
CategoryDescription
Product
ProductID(PK)
CategoryID(FK)
ProductName
ProductPrice
ProductDescription
ProductNumber
I would like to have 1 page per category.
On each page, I want the category name, the category Descripton.
And in a Table, I want the Product list.
How Can I perform this ?.
Thanks a lot.
First you need a query that gives you the information you want. This will be saved as your dataset within the report. This could be as simple as
SELECT c.CategoryName,
c.CategoryDescription,
p.ProductName,
p.ProductPrice,
p.ProductDescription,
p.ProductNumber
FROM Category c
JOIN Product p ON --insert join criteria here... like c.CategoryId = p.CategoryId
Name that dataset Products.
Next, drag a table onto your report. Define the dataset for the table to be the dataset you created above.
Create a group within the table, based on your Category primary key (CategoryName? some CategoryId?). Order this group by CategoryName (if you want alphabetical order).
Now in your table you can put the Category Name & Category Description in the group header of the table. All your product information will go in the table detail rows.
This will get you started. You can options at the group level to start a new page at the beginning of each group. You can also put in running totals (sums, averages, etc) that reset at a change in group.