Verwenden Sie die Where-Klausel im Datumsfeld mit PostgreSQL

Dieses Tutorial zeigt uns, wie man die Abfrage WHERE
im Feld date
durchführt. Es gibt mehrere Formate der Datum
-Darstellung; Im Allgemeinen wird es als string
oder varchar
zurückgegeben.
Manchmal tritt der Formatfehler auf. Alles, was Sie tun müssen, ist, die Spalte mit cast()
in einen date
-Typ umzuwandeln und sie dann in der where
-Klausel zu verwenden.
Verwenden Sie die WHERE
-Klausel im Date
-Feld mit PostgreSQL
Nehmen wir an, Sie haben eine Tabelle Benutzer
und sie hat ein Feld, das Datum
enthält.
create table Users (
id INT PRIMARY KEY,
full_name VARCHAR(50),
email VARCHAR(50),
register DATE
);
insert into Users (id, full_name, email, register)
values
( 1, 'Trula', '[email protected]', '2022-06-17'),
( 2, 'Ansel', '[email protected]', '2022-06-18'),
( 3, 'Baillie', '[email protected]', '2022-06-18'),
( 4, 'Lay', '[email protected]', '2021-11-23'),
( 5, 'Berton', '[email protected]', '2021-12-05'),
( 6, 'Malory', '[email protected]', '2022-01-31'),
( 7, 'Fernanda', '[email protected]', '2021-11-26'),
( 8, 'Hester', '[email protected]', '2022-03-13'),
( 9, 'Ced', '[email protected]', '2021-09-18'),
( 10, 'Tommy', '[email protected]', '2022-04-05');
select* from Users;
Ausgang:
id | full_name | email | register
----+-----------+----------------------------+------------
1 | Trula | [email protected] | 2022-06-17
2 | Ansel | [email protected] | 2022-06-18
3 | Baillie | [email protected] | 2022-06-18
4 | Lay | [email protected] | 2021-11-23
5 | Berton | [email protected] | 2021-12-05
6 | Malory | [email protected] | 2022-01-31
7 | Fernanda | [email protected] | 2021-11-26
8 | Hester | [email protected] | 2022-03-13
9 | Ced | [email protected] | 2021-09-18
10 | Tommy | [email protected] | 2022-04-05
(10 rows)
Nehmen wir an, wir möchten einen Benutzer sehen, der sich am 17/06/22
registriert hat, aber das Problem ist, dass es nicht das richtige Format für die Suche im Feld Datum
ist.
Wir müssen es also in das Format ISO-8601
konvertieren, sodass das Äquivalent des Formats ISO-8601
2022-06-17
lautet. Hier ist die zu suchende Abfrage:
SELECT *
FROM USERS
WHERE register::date = '2022-06-17';
Ausgang:
id | full_name | email | register
----+-----------+----------------------------+------------
1 | Trula | [email protected] | 2022-06-17
(1 row)
Sie können auch weitere Funktionen vom Typ Datum
ausprobieren. Zum Beispiel die Funktion date_trunc
.
SELECT * FROM USERS WHERE date_trunc('day', register) = '2022-06-17';
Ausgang:
id | full_name | email | register
----+-----------+----------------------------+------------
1 | Trula | [email protected] | 2022-06-17
(1 row)
Hier ist eine weitere Beispielabfrage:
SELECT * FROM USERS WHERE date_trunc('month', register) = '2022-06-17';
Ausgang:
id | full_name | email | register
----+-----------+-------+----------
(0 rows)s
Um mehr über das Datum
in Postgres zu erfahren, besuchen Sie die offizielle Dokumentation.