mysql, use condition in "where" - php

I have a database table like:
id name date price
1 a 2014-05-12 10
2 a 0000-00-00 20
3 a 2014-05-13 30
I want to search by date, and if the date exists, return the price of the date.
if the date does not exist, return the price of date 0000-00-00.
For example:
search by date:2014-05-12, return `10`
search by date:2014-05-20, return `30`
I have tried:
select price from table where (date=table.date or table.date='0000-00-00')
but it does not work.
How do I write the correct query?

Here is one method that uses order by and limit:
select t.price
from table t
where t.date in ('0000-00-00', #date)
order by t.date desc
limit 1;
Note that I changed the parameter name from date to #date to distinguish it from the column with the same name.

The syntax should table table.field (e.g. table.date), while in your example you have field.field (price.date).
Try:
select price from table where (table.date='{$date}' or table.date='0000-00-00')
Note that $date is a variable (assuming you use PHP). If you don't use PHP, you can't just write date as a variable here, but you can use #date.

Get the value of the field to be searched.Let it be $date_search.
if(!empty($date_search)) {
$sql = 'select price from table where date ='.$date_search;
mysql_query($sql);
}
else {
$sql = 'select price from table where date ="0000-00-00"';
mysql_query($sql);
}

Related

how can i group by different dates and sum each data on group dates

I am doing to Ad Tracking Panel.
I have 3 table on my database,
1- Campaigns
id
orderID
name
startDate
endDate
goal
type
status
unitPrice
total
2- Line Items
lineItem_id
id
lineItemOrderID
lineItemName
lineItemStartDate
lineItemEndDate
lineItemStatus
lineItemType
lineItemGoal
3- Line Items Statics
statics_id
lineItem_id
inventoryID
inventoryName
impression
click
staticsDate
My Table Example:
I want to like this result:
How can I group by different dates and sum each data on group dates
My Example Code: (It's not working true, the values false)
SELECT inventoryNameGI, SUM(impressionGI), SUM(clickGI)
FROM
(
SELECT DISTINCT inventoryName AS inventoryNameGI,
MAX(impression) AS impressionGI,
MAX(click) AS clickGI
FROM `line_items_statics`
WHERE `lineItemID` = '5'
AND staticsDate BETWEEN '2017-07-01 00:00:00'
AND '2017-07-03 23:59:59'
GROUP BY `inventoryName`
) AS toplamTablo
Try this - in your nested query, use CONVERT to convert DATETIME to DATE only.
SELECT INVENTORYID, SUM(IMPRESSION), SUM(CLICK), CONVERT(DATE,STATICSDATE)
FROM `line_items_statics`
WHERE `lineItemID` = '5'
AND normalDate BETWEEN '2017-07-01' AND '2017-07-03'
GROUP BY INVENTORYID,
CONVERT(DATE,STATICSDATE)

Unable to get "inbetween" records if year is different

I am having this unique bug
TABLE : tbl
id | title | iscancel | sold_dt
id: UID
Title : varchar
iscancel : 0/1
sold_dt : timestamp
select * from tbl where iscancel = 0 and DATE_FORMAT(sold_dt,"%m/%d/%Y") BETWEEN "06/01/2015" AND "03/01/2016" GROUP BY day(sold_dt) order by (sold_dt) asc
(note that year is different)
0 records returned
but if i do
select * from tbl where iscancel = 0 and DATE_FORMAT(sold_dt,"%m/%d/%Y") BETWEEN "06/01/2015" AND "12/01/2015" GROUP BY day(sold_dt) order by (sold_dt) asc
or
select * from tbl where iscancel = 0 and DATE_FORMAT(sold_dt,"%m/%d/%Y") BETWEEN "01/01/2016" AND "03/01/2016" GROUP BY day(sold_dt) order by (sold_dt) asc
(note that year is same)
-I'll get some records
*Used DATE_FORMAT because my calendar is giving me MM/DD/YYYY (i can not change since it might affect other areas)
what i am doing wrong?
Instead of converting the stored value into another format try changing the parameter itself to correct format. If you cant do it on your website you can do it in your query as well
sold_dt BETWEEN
STR_TO_DATE('06/01/2015', '%m/%d/%Y') AND STR_TO_DATE('03/01/2016', '%m/%d/%Y')
Try by passing static dates into DATE_FORMAT() function
select * from tbl where iscancel = 0 and DATE_FORMAT(sold_dt,"%m/%d/%Y") BETWEEN DATE_FORMAT("06/01/2015","%m/%d/%Y") AND DATE_FORMAT("03/01/2016","%m/%d/%Y") GROUP BY day(sold_dt) order by (sold_dt) asc

do something if (mysql)

i have made this:
$case=mysql_query("select * from project where url='$url'");
while($result=mysql_fetch_array($case))
{
$one = $result['date'];
$two = $result['time'];
}
$one contain the date of my article and $two contain the time of my article.
I need to do:
if $uno and $two is > of all row in my database called project do something.
Is possibile?
Update:
mysql information:
Date is "DATE" type and Time is "VARCHAR" type.
output example: 2016-02-10 - 12:22:18
Use this SQL instead:
select `date`, `time`
from project
where url='$url'
order by 1 desc, 2 desc;
Then the first record you get will also represent the most recent date/time combination.
If you are not interested in the other records, then add limit 1 to the SQL, and you will then only get one result:
select `date`, `time`
from project
where url='$url'
order by 1 desc, 2 desc
limit 1;

How can I create a SUM of one column within a query in SQL?

I have one table with multiple columns. I am needing to create an SQL query to display certain columns based off of the user input from a datepicker and a select box. I have done that just fine. However, I am needing one of the result columns to be totaled at the bottom of the display table. I cannot figure out how to create a result within my current query to display the totaled column. Essentially, I would like the WTTotal column to be totaled into a separate cell. My current query is below. I really think this is something simple that I just can't seem to see.
SELECT REPLACE(Client,',',' ') AS Client,WorkTicketNum,Lease,Date,OrderedBy,WTTotal
FROM WorkTicket
WHERE Date BETWEEN '2014-10-01' AND '2014-10-31' AND Invoiced IS NULL
ORDER BY Client
SELECT REPLACE(Client,',',' ') AS Client,WorkTicketNum,Lease,Date,OrderedBy,WTTotal
FROM WorkTicket
WHERE Date BETWEEN '2014-10-01' AND '2014-10-31' AND Invoiced IS NULL
ORDER BY Client
UNION ALL
SELECT 'Total', NULL, NULL, NULL, NULL, SUM(WTTotal)
FROM WorkTicket
WHERE Date BETWEEN '2014-10-01' AND '2014-10-31' AND Invoiced IS NULL;
You can't have it with a single query. Putting a SUM() into your query would require a GROUP BY clause and collapse all of your original result rows down into a single result row - meaning your table would disappear. What you want a is a client-side solution. e.g. Start a counter in your client code and manually add up the results. In pseudoish-code:
$sum = 0;
while( $row = fetch_from_db() ) {
$sum += $row['field_to_sum'];
display_row();
}
echo "Total: $sum";
If you want to have it in a separate column, not in a separate row, either you calculate it in a subquery and join it to your result:
SELECT REPLACE(Client,',',' ') AS Client,WorkTicketNum,Lease,Date,OrderedBy, my_calculated_sum AS WTTotal
FROM WorkTicket
JOIN (SELECT SUM(whatever_you_want_to_sum) as my_calculated_sum FROM WorkTicket) subquery_alias
WHERE Date BETWEEN '2014-10-01' AND '2014-10-31' AND Invoiced IS NULL
ORDER BY Client
Or you just calculate it with variables, like a running total. Your result is in the last row of the column.
SELECT REPLACE(Client,',',' ') AS Client,WorkTicketNum,Lease,Date,OrderedBy, #sum_variable := #sum_variable + whatever_you_want_to_sum AS WTTotal
FROM WorkTicket
, (SELECT #sum_variable := 0) var_init_subquery
WHERE Date BETWEEN '2014-10-01' AND '2014-10-31' AND Invoiced IS NULL
ORDER BY Client
But actually Kevin's solution is very good.
I also have similar solution as Kevin's :
;with cte_result
as
(
SELECT REPLACE(Client,',',' ') AS Client,WorkTicketNum,Lease,Date,OrderedBy,WTTotal
FROM WorkTicket
WHERE Date BETWEEN '2014-10-01' AND '2014-10-31' AND Invoiced IS NULL
)
select *
from cte_result
union
select 'TotalAmount',NULL,NULL,NULL,NULL,sum(WTTotal)
from cte_result
order by client
but this solution will work only if your DB Engine supports CTE.
with a CTE, we can use same resultset to get total's row.

How to order by a known id value in mysql

is it possible to order a select from mysql by using a known id first.
Example:
$sql = "SELECT id, name, date FROM TABLE ORDER BY "id(10)", id DESC
Not sure if the above makes sense but what I would like to do is first start ordering by the known id which is 10 which I placed in quotes "id(10)". I know that cannot work as is in the query but it's just to point out what I am trying to do.
If something similar can work I would appreciate it. Thanks.
SELECT id, name, date
FROM tbl
ORDER BY CASE WHEN id = 10 THEN 0 ELSE 1 END, id DESC
How about this?
SELECT id, name, date, IF(id = 10, 1, 0) AS sort_field
FROM TABLE
ORDER by sort_field, id DESC

Categories