簡體   English   中英

帶條件檢查的 MySQL 查詢

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM