我做到了:
SELECT u.username, u.abilitazione, u.email, u.nome, u.cognome, r.ruolo
FROM public.utenti AS u
JOIN public.ruoli_utente AS r
on u.username=r.username
WHERE r.ruolo='ROLE_ADMIN'
UNION
SELECT u.username, u.abilitazione, u.email, u.nome, u.cognome, r.ruolo
FROM public.utenti AS u
JOIN public.ruoli_utente AS r
on u.username=r.username
WHERE u.username
NOT IN (
SELECT username FROM public.ruoli_utente
WHERE ruolo='ROLE_ADMIN'
)
ORDER BY username;
我有两张桌子:
--- table utenti
CREATE TABLE public.utenti
(
username character varying(45) NOT NULL,
password character varying(45) NOT NULL,
abilitazione boolean NOT NULL DEFAULT true,
email character varying(45) NOT NULL,
nome character varying(45),
cognome character varying(45),
CONSTRAINT username PRIMARY KEY (username)
)
--- table ruoli_utente
CREATE TABLE public.ruoli_utente
(
user_role_id integer NOT NULL DEFAULT nextval('ruoli_utente_user_role_id_seq'::regclass),
username character varying(45) NOT NULL,
ruolo character varying(45) NOT NULL,
CONSTRAINT user_role_pk PRIMARY KEY (user_role_id),
CONSTRAINT username_fk FOREIGN KEY (username)
REFERENCES public.utenti (username) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION
)
从这个查询中我获得了项目中需要的所有信息:
SELECT u.username, u.abilitazione, u.email, u.nome, u.cognome, r.ruolo
FROM public.utenti AS u
JOIN public.ruoli_utente AS r
on u.username=r.username
ORDER BY username
但我希望获得一行,其中用户具有ROLE_ADMIN的角色(在示例中没有行3和4的结果)。我该怎么办?
答案 0 :(得分:-1)
我解决了这个问题:
SELECT u.username, u.abilitazione, u.email, u.nome, u.cognome, r.ruolo
FROM public.utenti AS u
JOIN public.ruoli_utente AS r
on u.username=r.username
WHERE r.ruolo='ROLE_ADMIN'
UNION
SELECT u.username, u.abilitazione, u.email, u.nome, u.cognome, r.ruolo
FROM public.utenti AS u
JOIN public.ruoli_utente AS r
on u.username=r.username
WHERE u.username
NOT IN (
SELECT username FROM public.ruoli_utente
WHERE ruolo='ROLE_ADMIN'
)
ORDER BY username;