[英]MySQL query with conditions check
我有一个包含用户详细信息的表格。 现在我需要执行一个满足以下条件的 MySQL 查询:
有两张桌子
1) 用户表 - 包含用户 ID、姓名、名字
2) 类别表 - 其中包含类别 ID、类别类型、分配的用户 ID
现在我想执行满足以下条件的查询
用户只能看到一个类型为 simple、complex 的类别,这些类别仅分配给他的用户 ID,而该类别不应分配给任何其他用户 ID。
任何人都请帮助我。
drop table if exists category;
create table category (id int, categorytype varchar(10), assignedUserId int);
truncate table category;
insert into category values
(1,'simple',1),
(2,'complex',1),
(3,'simple',2),
(4,'complex',3),
(5,'odd',1);
MariaDB [sandbox]> select * from users where id < 6;
+----+----------+----------+--------+---------------------+
| id | userName | photo | status | ts |
+----+----------+----------+--------+---------------------+
| 1 | John | john.png | 1 | 2016-12-08 13:14:24 |
| 2 | Jane | jane.png | 1 | 2016-12-08 13:14:24 |
| 3 | Ali | | 1 | 2016-12-08 13:14:24 |
+----+----------+----------+--------+---------------------+
3 rows in set (0.00 sec)
MariaDB [sandbox]>
MariaDB [sandbox]> select u.*, c.*
-> from users u
-> join category c on c.assigneduserid = u.id
-> where u.id = 1
-> and c.categorytype not in (select c.categorytype from category c where c.assigneduserid <> 1);
+----+----------+----------+--------+---------------------+------+--------------+----------------+
| id | userName | photo | status | ts | id | categorytype | assignedUserId |
+----+----------+----------+--------+---------------------+------+--------------+----------------+
| 1 | John | john.png | 1 | 2016-12-08 13:14:24 | 5 | odd | 1 |
+----+----------+----------+--------+---------------------+------+--------------+----------------+
1 row in set (0.00 sec)
尝试这个:
SELECT *
FROM category c
where userid = 123
and not exists (
select 1
from category c2
where c.userid <> c2.userid
and c.categorytype = c2.categorytype
);
请注意,与其他答案不同,此查询不需要在两个地方提及 id,因此是一个更通用的查询。
SELECT * FROM categories
WHERE category_type = 'simple' OR
category_type = 'complex' AND // (edited after comment of Philipp)
assinged_userid = (Your User ID Here)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.