select all sales from specific day ? mysql , convert datetime to date - mysql

how to convert the DateTime column to date?
I need something like the select * from sales where date = = "2022-09-18";
I need to get all sales from a specific day
I tried this How can I convert datetime to date, truncating the times, leaving me the dates?
and many more solutions but nothing is working.
i tried this SELECT DATE(datatime) AS date_of_booking FROM sales; " ;
but it gave me this
I tried also this but it gave me error this
this is a table named Sales
if there is anybody that can help me understand how do I get this thing to work please i really appreciate that! a lot .
code for generating the database if you want
DROP DATABASE IF EXISTS ice_cream_store;
CREATE DATABASE IF NOT EXISTS ice_cream_store;
USE ice_cream_store;
CREATE TABLE `Tastes` (
`tid` INTEGER NOT NULL AUTO_INCREMENT primary key,
`name` VARCHAR(20) NOT NULL,
UNIQUE (name)
);
CREATE TABLE `Toppings` (
`topid` INTEGER NOT NULL AUTO_INCREMENT primary key,
`name` VARCHAR(20) NOT NULL,
UNIQUE (name)
);
CREATE TABLE `Receptacles` (
`rid` INTEGER NOT NULL AUTO_INCREMENT primary key,
`name` VARCHAR(20) NOT NULL,
`price` int NOT NULL,
UNIQUE (name)
);
CREATE TABLE `Sales` (
`sid` INTEGER NOT NULL AUTO_INCREMENT primary key,
`rid` integer not null,
foreign key (`rid`) references Receptacles(`rid`),
`datetime` datetime not null,
`completed` bool not null,
`paid` bool not null,
`total_price` INTEGER NOT NULL
);
CREATE TABLE `Tastes_Sales` (
`sid` integer not null,
foreign key (`sid`) references Sales(`sid`),
`tid` integer not null,
foreign key (`tid`) references Tastes(`tid`),
PRIMARY KEY (`sid` , `tid`),
`quantity` integer not null
);
CREATE TABLE `Toppings_Sales` (
`sid` integer not null,
foreign key (`sid`) references Sales(`sid`),
`topid` integer not null,
foreign key (`topid`) references Toppings(`topid`),
PRIMARY KEY (`sid` , `topid`)
);
SELECT
DATE(`datatime`)
AS date_of_booking
FROM sales;
select * from tastes;
select * from Receptacles;
select * from Toppings;
select * from sales;
select * from Toppings_Sales;
select * from Tastes_Sales;

Use the extract function
Example:
SELECT EXTRACT(MONTH FROM "2017-06-15 09:34:21");
outputs 6
From there you just do:
select * from sales where EXTRACT(DAY FROM date) = 18;
Now you just add AND operators to do the same for month and year
I think this is a simple enough solution. Hope this works for you.

SELECT * from sales WHERE DATE(datetime) = '2022-09-15'; this is working for me #RiggsFolly thank you very much!!

Related

Set a unique constraint only when a field is null

I have this table:
CREATE TABLE `executed_tests` (
`id` INTEGER AUTO_INCREMENT NOT NULL,
`user_id` INTEGER NOT NULL,
`test_id` INTEGER NOT NULL,
`start_date` DATE NOT NULL,
`completed_date` DATE,
PRIMARY KEY (`id`)
);
I want to set up an unique constraint on fields user_id and test_id, but only when conclusion_date is null. If conclusion_date is not null, the constraint doesn't apply.
So there will exist only one incomplete execution per user and test.
Something like this:
UNIQUE(`user_id`, `test_id`) WHEN (`completed_date` IS NULL)
How can I accomplish this on MySQL 5.6?
MySQL supports functional key parts since 8.0.13.
If your version is sufficiently recent you can define your index as:
UNIQUE(`user_id`, `test_id`, (IFNULL(`completed_date`, -1)))
(Demo on dbfiddle.uk)
Note that the above index will also prevent duplciate dates for completed executions. If those should be valid then a slightly modified index would work:
UNIQUE(`user_id`, `test_id`, (
CASE WHEN `completed_date` IS NOT NULL
THEN NULL
ELSE 0
END))
(Demo on dbfiddle.uk)
Although then it starts to feel a bit dirty ;)
If you have at least version 5.7 you can use a (virtual) generated column as workaround:
CREATE TABLE `executed_tests` (
`id` INTEGER AUTO_INCREMENT NOT NULL,
`user_id` INTEGER NOT NULL,
`test_id` INTEGER NOT NULL,
`start_date` DATE NOT NULL,
`completed_date` DATE,
`_helper` CHAR(11) AS (IFNULL(`completed_date`, -1)),
PRIMARY KEY (`id`),
UNIQUE(`user_id`, `test_id`, `_helper`)
);
(Demo on dbfiddle.uk)
If you are stuck on 5.6 then a combination of a regular (non-virtual) column and slightly modified INSERT statements would work:
CREATE TABLE `executed_tests` (
`id` INTEGER AUTO_INCREMENT NOT NULL,
`user_id` INTEGER NOT NULL,
`test_id` INTEGER NOT NULL,
`start_date` DATE NOT NULL,
`completed_date` DATE,
`is_open` BOOLEAN,
PRIMARY KEY (`id`),
UNIQUE(`user_id`, `test_id`, `is_open`)
);
In this case you would set is_open to true for incomplete executions and to NULL after completion, making use of the fact that two NULLs are treated as not equal.
(Demo on dbfiddle.uk)

Correct structure and index for a Weekly table

I need a table to store text every week for each user.
So I thought two alternatives:
1) Using composite primary key:
CREATE TABLE `WeeklyTxt` (
`Year` YEAR(4) NOT NULL ,
`Week` ENUM('1','2','3','4', ... ,'51','52','53') NOT NULL ,
`UserId` BIGINT NOT NULL ,
`WeekTxt` TEXT NOT NULL,
PRIMARY KEY (`Year`, `Week`, `UserId`)
) ENGINE = InnoDB;
2) Using autoincrement primary key
CREATE TABLE `WeeklyTxt_2` (
`WeekTxtId` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
`Year` YEAR(4) NOT NULL ,
`Week` ENUM('1','2','3','4', ... ,'51','52','53') NOT NULL ,
`UserId` BIGINT NOT NULL ,
`WeekTxt` TEXT NOT NULL
) ENGINE = InnoDB;
I can't figure out what could be the better choice (and why)
It depends of the search in the table that you will usually do!
Tipically I would use a Simple PRIMARY KEY, and I will add another KEY like your KEY: (Year, Week, UserId)

Trouble with Date fields & Combining data from 2 tables

I'm having a MySQL Database, created using the following code (sure there are other tables too, but they're not relevant as per this specific question) :
DROP TABLE IF EXISTS `Jeweller`.`Product_sales`;
CREATE TABLE `Jeweller`.`Product_sales` (
`sale_id` int(11) unsigned NOT NULL,
`product_id` int(11) NOT NULL,
`quantity` int(11),
`value` float,
FOREIGN KEY (`sale_id`) REFERENCES `Jeweller`.`Sales`(`id`),
FOREIGN KEY (`product_id`) REFERENCES `Jeweller`.`Products`(`id`),
CHECK (`quantity`>0),
CHECK (`value`>0)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
DROP TABLE IF EXISTS `Jeweller`.`Products`;
CREATE TABLE `Jeweller`.`Products` (
`id` int(11) unsigned NOT NULL,
`product_category_id` int(11) NOT NULL,
`seller_id` int(11) NOT NULL,
`name` varchar(100) NOT NULL,
`description` text,
PRIMARY KEY (`id`),
FOREIGN KEY (`product_category_id`) REFERENCES `Jeweller`.`Product_categories`(`id`),
FOREIGN KEY (`seller_id`) REFERENCES `Jeweller`.`Sellers`(`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
DROP TABLE IF EXISTS `Jeweller`.`Sales`;
CREATE TABLE `Jeweller`.`Sales` (
`id` int(11) unsigned NOT NULL,
`date` date DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
How would you go about finding :
Total earnings (quantity*value) per month (in 2013 - or any specific year for that matter)
I started by trying to get the month out of a DATE field (using DATEPART) but I'm already into trouble...
So, any ideas?
P.S.
I'm not a guru with SQL
The above is just an example, and not the exact code
SELECT MONTH(s.date) month, SUM(p.quantity * p.value)
FROM Jeweller.Sales s
JOIN Jeweller.Product_sales p ON p.sale_id = s.id
WHERE s.date >= '2013-01-01' AND s.date < '2014-01-01'
GROUP BY month
Note that if the date range spans multiple years, you will need to group on both year and month.

mysql table with multiple primary key compound constraint

I'm sorry if the title isn't exactly.. useful, but I wasn't sure how to explain my issue in a title.
So basically, I want to create a table like that :
reservation
day
room
id_client
[other_stuff]
For a given day+room, you can get the id_client + everything else. And also for a given id_client + day you can get the room + other stuff.
I don't exactly understand how am I supposed to say that the compound day+room must be unique AND the compound day+id_client must also be unique. I really need both of those constraint in my database.
Anyone has an idea ?
Thanks.
Define one combination an PRIMARY KEY and the other as UNIQUE key:
CREATE TABLE reservation
( day
, room
, id_client
, [other_stuff]
, PRIMARY KEY (day, room)
, UNIQUE KEY (id_client, day)
) ;
or the other way around:
CREATE TABLE reservation
( day
, room
, id_client
, [other_stuff]
, PRIMARY KEY (id_client, day)
, UNIQUE KEY (day, room)
) ;
Or, if you already have another Primary Key, make them both unique:
CREATE TABLE reservation
( reservation_id
, day
, room
, id_client
, [other_stuff]
, PRIMARY KEY (reservation_id)
, UNIQUE KEY (id_client, day)
, UNIQUE KEY (day, room)
) ;
-- in MySQL
drop database if exists mydatabase;
create database mydatabase;
use mydatabase;
drop table if exists client;
create table client
(
id int unsigned not null auto_increment,
name varchar(45) not null,
primary key (id)
)engine=InnoDB default charset=utf8;
drop table if exists room;
create table room
(
id int unsigned not null auto_increment,
label varchar(45) not null,
primary key (id)
)engine=InnoDB default charset=utf8;
drop table if exists reservation;
create table reservation
(
id int unsigned not null auto_increment,
id_room int unsigned,
id_client int unsigned,
day date,
unique(day, id_room),
unique(day, id_client),
foreign key (id_room) references room(id),
foreign key (id_client) references client(id),
primary key (id)
)engine=InnoDB default charset=utf8;
There are two ways of looking at this... are the unique constraints you mention mutually exclusive? Meaning, can one exist without the other?
Logic dictates that a room can be booked to one day at a time, regardless of client. Unless multiple clients can share the same room. So I will give you two alternatives.
# If room can be booked to multiple clients
CREATE TABLE `reservation` (
`id` int(11) unsigned not null auto_increment,
`day` varchar(25) not null,
`room` int(5) unsigned not null,
`id_client` int(11) unsigned not null,
PRIMARY KEY (`id`),
UNIQUE KEY (`room`, `day`),
UNIQUE KEY (`room`, `id_client`),
)ENGINE=InnoDB DEFAULT CHARSET=utf8;
# Room can only be booked to one client for a given day
CREATE TABLE `reservation` (
`id` int(11) unsigned not null auto_increment,
`day` varchar(25) not null,
`room` int(5) unsigned not null,
`id_client` int(11) unsigned not null,
PRIMARY KEY (`id`),
UNIQUE KEY (`room`, `day`)
)ENGINE=InnoDB DEFAULT CHARSET=utf8;
Also, I would use a separate primary key column, otherwise your updates will be more complex, for example:
UPDATE `reservation` SET `other_stuff` = 'some value' WHERE `day` = 'Friday' AND `room` = 123;
# Vs
UPDATE `reservation` SET `other_stuff` = 'some value' WHERE `id` = 1;

How can I select the current holder for each championship?

I want to select the current holders for each championship in a championships table, and return NULL for championships that have not had any winners yet.
Here are the create statements for the two tables:
CREATE TABLE `championships` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`friendly_name` varchar(255) NOT NULL,
`rank` int(2) unsigned NOT NULL DEFAULT '1',
PRIMARY KEY (`id`),
UNIQUE KEY `name` (`name`),
UNIQUE KEY `friendly_name` (`friendly_name`)
) ENGINE=InnoDB;
CREATE TABLE `title_history` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`championship` int(10) unsigned NOT NULL,
`winner` varchar(255) NOT NULL,
`date_from` date NOT NULL,
`location` varchar(255) NOT NULL,
PRIMARY KEY (`id`),
KEY `championship` (`championship`)
) ENGINE=InnoDB;
ALTER TABLE `title_history` ADD CONSTRAINT `title_history_ibfk_1` FOREIGN KEY (`championship`) REFERENCES `championships` (`id`) ON UPDATE CASCADE;
What MySQL statement would return the data set I wanted?
Assuming you're storing the winner of a championship as the primary key/id of the holder, something like this should work. You might want to add in another join to get the actual name of the team from another table though.
Because LEFT join will only select rows from the 'right' table when there is a match, everything that doesn't have one should come back as NULL.
SELECT name, [holder]
FROM championships AS c
LEFT JOIN title_history AS h ON c.winner = h.id
EDITED VERSION:
With further insight into your tables and from your comment, maybe try this subselect:
SELECT friendly_name,
(SELECT winner FROM title_history WHERE championship = c.id ORDER BY date_from DESC LIMIT 1)
FROM championships AS c
ORDER BY name
If I understand your structure correctly, that ought to get the last winner of each championship?