computed column to use further in mysql query [duplicate] - mysql

This question already has answers here:
Can I reuse a calculated field in a SELECT query?
(7 answers)
Closed 3 years ago.
I want to know how can i use two columns already computed in sql query to get one more result from their values.
my query is
SELECT s.date date
, p.id
, SUM(COALESCE(p.avgcost,0)) costofsale
, SUM( COALESCE(s.actual_payable, 0 ) ) total_sales
, (total_sales - costofsale) tots
FROM sales s
LEFT
JOIN sale_items si
on si.sale_id = s.id
LEFT
JOIN products p
on p.id = si.product_id
WHERE DATE(s.date) = DATE('2019-09-10 14:48:50')
I want to get the result from total_sales - costofsale that is already computed in query.
I don't want to alter or update my table.
I just need to use those two columns to give me the result by calculating them.
I have not found any solution over google.

MySQL 8 includes WITH statements which allows for creating calculated values without using variables.
WITH statement VS subquery

Related

mysql checking if product ID also exist in other table [duplicate]

This question already has answers here:
Select rows which are not present in other table
(4 answers)
Closed 2 years ago.
I have not much experience with JOINS and the result I get with query below isn't correct.
I have a table called products and want to check if there are records in the table product_links.
I only want to get a list of items that doesn't have rows in product_links.
When I run the below query, I only get one line.
Anybody suggestions? Google couldn't help me or I'm searching with the wrong keywords.
SELECT a.id, a.SKU, a.title,
(SELECT COUNT(b.id) AS amount FROM product_links WHERE b.product=a.id) AS amount
FROM products AS a
LEFT JOIN product_links AS b ON b.product=a.id
I would recommend not exists:
select p.*
from products p
where not exists (select 1 from product_links pl where pl.product_id = p.id)
From your question i understand you need info of products which doesnt have any links.
Below is the query for that
SELECT * FROM products
WHERE id NOT IN (SELECT id FROM product_links);

How to remove duplicate results? [duplicate]

This question already has answers here:
Retrieving the last record in each group - MySQL
(33 answers)
Closed 3 years ago.
I'm coding a message system using mysql.
Everything works fine when I list users whom I'm conversing with, until I want to add date of the last or the start of conversation.
When I add a.date I get duplicate results when the date isnt the same.
Here is my sqlfiddle
Since, you were pulling only user_id then in both cases (send/recieve) it was giving you distinct record. But now with date it is no more distinct. you need to do something like:
SELECT temp.id_user, MAX(temp.date) as date
FROM
(
SELECT users.id_user,
a.date
FROM users
LEFT JOIN message AS a
ON users.id_user = a.id_user_recipient
LEFT JOIN message AS b
ON a.id_user_recipient = b.id_user_sender
WHERE a.id_user_sender = 1
UNION DISTINCT
SELECT users.id_user,
a.date
FROM users
LEFT JOIN message AS a
ON users.id_user = a.id_user_sender
LEFT JOIN message AS b
ON a.id_user_sender = b.id_user_recipient
WHERE a.id_user_recipient = 1
) as temp
GROUP BY temp.id_user;
Grabbing max(date) will ensure to return only one record as with group by

MAX(date) Not Returning Latest Date [duplicate]

This question already has answers here:
SQL select only rows with max value on a column [duplicate]
(27 answers)
Closed 5 years ago.
I am joining three tables and I am trying to show the latest date but the dates that are being returned are not the latest.
SELECT c.id, c.companyname,c.displayname, c.address1, c.address2,
c.town, c.postcode,cd.contactname cd.contactphone, cd.contactemail,
MAX(q.coldate)
FROM companies c, query q, custd cd
WHERE c.id = q.id AND q.id = cd.compid
AND year(q.coldate) >= 2016
GROUP BY q.companyname;
How can I fix this please?
if you want to display the max(date) in your table (and therefore the same date) for every row of your result, try this before you run the query:
select cast(max(coldate) as char) from schema_name.table_name into
#max_coldate_for_query ;
when running your query change coldate to #max_coldate_for_query in the list of columns you are selecting

MySql sort on join? [duplicate]

This question already has answers here:
SQL select only rows with max value on a column [duplicate]
(27 answers)
Closed 6 years ago.
I have two tables jobs, notes.
I want to output a list of jobs that are of status='lost' along with the most recent note for that job (based on the date the note was created).
Here's my query:
select jobs.id, jobs.name, jobs.status
inner join notes on jobs.id=notes.jobId
where jobs.status='lost'
group by jobs.id
order by notes.createDate DESC
I would have thought that the output would show the most recent note for a given job. But it shows the first note for that job. I have changed sort from DESC to ASC just to see what happens...and the output is the same.
Then I tried to nest a select from notes inside the main select..and it hung.
This should be easy and I am sure it is..what am I missing ?
There is many options to solve this, but you may use a sub query.
select jobs.id, jobs.name, jobs.status
(select noteField from notes on jobs.id=notes.jobId order by createDate desc limit 1) note
where jobs.status='lost'
When I'm in a similar boat, I've resorted to using a subquery on the join:
select jobs.id, jobs.name, jobs.status
from jobs
inner join notes on jobs.id = notes.jobId
and notes.createDate = (select max(notes.createDate)
from notes
where jobs.id = notes.createDate
group by notes.jobId)
where jobs.status='lost'
group by jobs.id
order by notes.createDate DESC

MySQL query multiple table inner join [duplicate]

This question already has an answer here:
Syntax error due to using a reserved word as a table or column name in MySQL
(1 answer)
Closed 8 years ago.
I have this MySQL query but it seems to be getting an error while I try to run it. Since I'm a newbie I'd like some advice of what I should do to correct it. I just want to show the name, quantity and order date of the orders that has 1 or more pending products. Thanks a lot!
select product.name, order_details.quantity, order.date from product,order_details,order
inner join order on order_details.order_id=order.id
inner join product on order_details.product_id=product.id
inner join customer on order.cust_id=costumer.id WHERE order.pending=>1
You have a table called order. This word has special significance in SQL. Your options are to rename the table, or quote it whenever you want to query from it.
Easiest solution is to change.
inner join order ....
to
inner join `order`
Be sure to use back-quotes around the table name.
You have a table named 'order', which is a reserved word in SQL.
One solution is to prefix the table name with the database name as explained in Craic Computing blog
Another one is to wrap the table name with the ` character as you can read in this StackOverflow question
You can try something like :
SELECT product.name, order_details.quantity, `order`.date
FROM product
INNER JOIN order_details ON product.id = order_detail.product_id
INNER JOIN `order` ON `order`.id = order_detail.order_id
WHERE `order`.pending >= 1
As said in other answers, orderis a reserved keyword in SQL, surround it with backquotes.
Maybe you should store the pending information in the order_detail table (1 if pending, 0 if not), in order to keep track of which product is still pending instead of incrementing/decrementing the order.pending field.
In this case, you could make the following query :
SELECT product.name, order_details.quantity, `order`.date
FROM product
INNER JOIN order_details ON product.id = order_detail.product_id
INNER JOIN `order` ON `order`.id = order_detail.order_id
WHERE `order_detail`.pending = 1
Which would return all the products still pending in your orders instead of every product from orders in which maybe only one is pending.