具有条件检查的MySQL查询

时间:2017-01-07 10:17:48

标签: php mysql mysqli phpmyadmin

我有一个表格,其中包含用户详细信息。现在我需要执行满足以下条件的MySQL查询:

有两个表

  

1)用户表 - 包含userid,name,firstname

     

2)类别表 - 包含categoryid,类别类型,assinged userid

现在我想执行满足以下条件的查询

用户只能看到类型简单,复杂且仅分配给其用户ID的类别,并且该类别不应分配给任何其他用户ID。

任何人都可以帮助我。

3 个答案:

答案 0 :(得分:2)

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)

答案 1 :(得分:1)

试试这个:

return false

请注意,与其他答案不同,此查询不需要在两个地方提及id,因此更为通用。

答案 2 :(得分:0)

SELECT * FROM categories 
WHERE category_type = 'simple' OR 
      category_type = 'complex' AND // (edited after comment of Philipp)
      assinged_userid = (Your User ID Here)