How to make this one to many query? - mysql

I need help makeing this selection.
Those are the 2 tables.
First table:
-there are Unique/Primary buyID-s( we can say that here buyID is and Order)
-distID-s can be many.
Second table:
-This table does not have an unique indentifier
-same buyID here ca more than one(basically buyID here offers more details on order, offers the a list of products for that order(buyID) from first table.
What I am trying to do, but I can't figure how to write the query:
-Select all buyID-s Where distID=119 From table 1(buyID-s will be 1724,1833 and 1890)
-From Table 2, sum the quantity, where buyID(from table2)=buyID(from table1).
As a result I must have:
distID=119
buyID=1724--------quantity=25 (as an example)
buyID=1833--------quantity=60
buyID=1890--------quantity=23(if there will also be the product_number list, will be awesome)
I hope this make sense.
I am not too much experienced,I am trying for # an hour, I am sure is not too hard, but this piss me of...
I am waiting for abit of help.
Thanks

Use LEFTJOIN and GROUP BY
select t1.distID, t2.buyID,sum(t2.quantity) as quantity
from table1 t1
left join table2 t2 on t2.buyID = t1.buyID
where t1.distID = 119
group by t1.distID, t2.buyID
If you also want to include product_number in resultset, then you have to select them using aggregate function like MAX(product_number) as product_number since the query use GROUP BY clause.

select sum(quantity) from Table2 where buyID in (select buyID from Table1 where distID=119)

Related

WHERE clause with INNER JOIN and Sub Query

I have achieved my desired query but I want to know how this one worked. I have multiple tables on my database and my requirements was to take the id from table called product and using this id, I want to retrieve some data from multiple tables and product id is a foreign key to the other tables. The query below works fine (by the way I was just experimenting and luckily got this query).
SELECT ponsfdp.*, product.pName, product.pImage, product.productSizes FROM product
INNER JOIN priceOnSizesForDigitalPrinting AS ponsfdp ON ponsfdp.pId_fk =
(SELECT pId FROM product WHERE pName LIKE "%booklet%")
WHERE pName LIKE "%booklet%";
But when I tried this query,
SELECT ponsfdp.*, product.pName, product.pImage, product.productSizes FROM product
INNER JOIN priceOnSizesForDigitalPrinting AS ponsfdp ON ponsfdp.pId_fk =
(SELECT pId FROM product WHERE pName LIKE "%booklet%");
It contains all the data even with null fields too. Can someone explain to me how it works? My personal opinion is both query should return same data because on the second query, I am using a subquery and it returns only one id, on the other hand, first query has a WHERE clause which generates the same id but by the help of name. How does the first query returns very specific columns and second return all columns even null columns too? I need an explanation for both queries.
Your first query also returning all rows as returned from your second query. But, when you are adding the last filter-
WHERE pName LIKE "%booklet%"
It's just keeping one single row from all rows where pName is like 'booklet'. You can consider the output from your second query as a single table and your logic working as below-
SELECT * FROM (
SELECT ponsfdp.*, product.pName, product.pImage, product.productSizes
FROM product
INNER JOIN priceOnSizesForDigitalPrinting AS ponsfdp
ON ponsfdp.pId_fk = (SELECT pId FROM product WHERE pName LIKE "%booklet%")
)A
WHERE pName LIKE "%booklet%"
Hope this will at least give you some insight of your query.
I don't see any need for a subquery here. You should be using the where condition to select rows from your FROM table, then use the ON clause of your join to find the right record(s) in your joined table for each row of the FROM table:
SELECT ponsfdp.*, product.pName, product.pImage, product.productSizes
FROM product
INNER JOIN priceOnSizesForDigitalPrinting AS ponsfdp
ON ponsfdp.pId_fk = pId
WHERE pName LIKE "%booklet%";

MySQL SELECT DISTINCT how to join some corresponding columns to query result

I have a table with
id,column1, column2, column3,column4,column5
MySQL SELECT DISTINCT returns me exactly what I need and this query must remains exactly AS IS
SELECT DISTINCT column1,column3 from tablename
But as an output I have only 2 columns as requested in DISTINCT query above
column1,column3
Question - how to join to this result other corresponding columns from the same table ?
For example
column1,column3,id,column5
Spent a couple of hours in Google, the two 'nearest' idea is something like
SELECT DISTINCT column1,column3
from tablename AS tbl1
INNER JOIN (SELECT id,column5 from tablename) AS tbl2
But such a query anyway returns me ONLY
column1,column3
My Expected result should be
column1,column3 (exactly as a result of SELECT DISTINCT) + two other columns id,column3 - so that I could save this result to a new table with 4 columns.
But I have only two columns as I told above.
EXAMPLE added
http://sqlfiddle.com/#!9/1e4472/1
Please, pay attention - the query result does not show ID 4 because this ID has duplicates in BOTH fields - company and city. So this is exactly what I need.
So, HOW to show in results not only COMPANY and CITY, but also, for example, ID and MANAGER ?
In case of duplication, if you want to display the first(original) record with the same values of company & city (i.e. like here you want to show id=1 not id=4) then following query should work:
SELECT min(id) as id,manager,company,city
FROM DistinctResult
group by company,city;
Click here for Demo
Hope it helps!
Simply :
SELECT DISTINCT Column1,Column3,id,column5
Or alternatively , if there is more than 1 value for these columns:
SELECT Column1,Column3,MAX(id),MAX(column5)
GROUP BY Column1,Column3
But it really depends on the requirement and you weren't very clear.

Mysql Database - Average value

Here's a question:
Using appropriate column names, show admit id and average obs value for obs type 'CONT' where the average obs value of the CONT is >= 40.
Lets say admit is table1 and observe is table2 but with the same primary key Admit_id. I'm trying to get the result where average of obs value is greater than 40 but
however I got this error instead: Unknown column 'Average' in 'where clause. Any solution here?
Select
ADMIT.Admit_id,
(SELECT AVG(Obs_value) FROM OBSERVE) AS Average
from
ADMIT,OBSERVE
Where
ADMIT.Admit_id=OBSERVE.Admit_id
AND
OBSERVE.Obs_type = 'CONT'
AND
Average >=40;
you should try joining the two tables and you cant reference an alias inside the WHERE .. it has to be HAVING. so something like this..
SELECT a.Admit_id, AVG(o.Obs_value) AS Average
FROM ADMIT a
JOIN OBSERVE o ON o.admit_id = a.admit_id
WHERE o.Obs_type = "CONT"
GROUP BY a.Admit_id
HAVING Average >=40;
Think of it this way...
SELECT is making an order at a restaurant....
FROM and JOIN is saying what menu's you want to order from....
WHERE is any customization you want to make to your order (aka no mushrooms)....
GROUP BY and anything after is after the order has been completed and is at your table...
ORDER BY is saying what dishes you want first (aka i want my entree then dessert then appetizer ).
HAVING can be used to pick out any mushrooms that were accidentally left on the plate....
etc.. I know its a weird analogy but its a good way to understand how it works..
the alias to a table cannot be referenced until you create that table with your select you could also make it a sub select and do the same thing with a WHERE like so
SELECT *
FROM
( ... your_inner_select -- without the HAVING
)t -- every table must have an alias
WHERE t.Average >=40

MYSQL - QUERY FROM TWO TABLES

Question - let's say I have 2 tables.
Table 1 - name is permission_list, columns are ID (unique ID), col_ID, user_ID
Table 2 - name is list_entries, Columns are ID (unique ID), title, description, status
I want to select all the rows from table 2 that have status of 'public' as well as all the rows from table 2 that the ID from table 2 shows up in table 1 (under the column col_ID) AND if the user_ID in table 1 matches a certain value. So, anything public, or anything that this specific user has listed under the permissions table. This query would also remove duplicates - in case the user gets a public entry listed in their permissions_list, it wouldn't show up twice.
Hope that makes sense!
Here you go:
SELECT DISTINCT table2.* from table2
LEFT JOIN table1 USING (id)
WHERE status='public'
OR user_ID='someuser';
You need to get some education on JOIN for your first thing, and the second thing is called DISTINCT.
Start here... https://www.google.com/
You have not specified your join condition so we can't give you code samples really. Also the way you worded your question, I'm not entirely sure you don't want a UNION. Read up on those concepts and come back here when you can improve the question.
SELECT table_2.status, table_2.ID, table_1.col_ID
FROM table_1 JOIN table_2
WHERE table_2.status = 'public'
AND table_2.ID = table_1.col_ID
AND table_1.user_ID = 'certain value'
;
Try this

Get max row per group from a related table

This is my first time asking a question on here. It has been very helpful with learning.
I am trying to select a table and getting only rows that have a maximum value for its particular group in another table. One of the best answers that is very close but not quite there is this one (SQL Select only rows with Max Value on a Column) but it only relates to a single table. I have found some others with multiple table but not sure how exactly to use it.
I have a table with (simplified)
prodID, quantity, mach, etc
I then have a table with
prodStatusID, prodID, userID, subStatusID
a last table with sub status names
subStatusID, subStatusName
I am trying to get a table with all of the first table and the second table but only with the row that has the maximum status number and include the right status name.
My other concern which may not matter now but in a year or two when this thing starts to really fill up is performance. I dont know bad it is to have select inside a select but if I am trying to return all productions then it will be doing a query for every production.
Just to be clearer. in the second table prodStatus there might be 2 rows with prodID of 4 but the subStatusID for the first one would be 1 and the second one would be 2. The userID will be different. All I want to get back is the second row because it has the highest status number and I need the userID and statusName associated with that row.
I have been googling for 2 days to get this answer and I saw 1 about auctions but I just dont fully understand it even after researching it.
You need to create a subquery which get the maximum value of subStatusID for each prodID.
SELECT a.*, -- select only columns that you want to show
c.*, -- asterisks means all columns
d.*
FROM table1 a
INNER JOIN
(
SELECT prodID, max(subStatusID) maxID
FROM table2
GROUP BY prodID
) b ON a.prodID = b.prodID
INNER JOIN table2 c
ON b.prodID = c.prodID AND
b.maxID = c.subStatusID
INNER JOIN table3 d
ON c.subStatusID = d.subStatusID