在一个查询中使用Delete和Select子句

时间:2015-05-01 10:37:04

标签: mysql

我有三张桌子。


circle
id   name 
1     first
2     two
3     three
4     four

user_circle

user_id  circle_id  user_type_id
1        1          1
1        2          1
1        3          1
1        4          2
2        2          2


user_type

id  type
1   admin
2   member

我想删除user_id = 1和user_type_id = 1的圈子,该圈子中的用户数量为1。如何在一个查询中执行此操作?

我需要一个从表格中删除以下圈子的结果。

circle_id
1
3

2 个答案:

答案 0 :(得分:0)

首先选择只有一个用户的DELETE。然后,您必须创建一个子查询并使其成为别名,因为您无法更新刚刚从中选择的表。最后,使用WHERE并应用您需要的所有DELETE FROM users WHERE circle_id IN ( SELECT * FROM ( SELECT circle_id FROM users GROUP BY circle_id HAVING (COUNT(user_id)=1) ) AS u ) AND user_id = 1 AND user_type_id = 1 条件。

   $pr_dt=$_POST['hid'];//div elements which i want ot convert them to pdf and also contain bootstap lib link
   include_once("../assets/converter/dompdf/dompdf_config.inc.php");
   $dompdf =  new DOMPDF();
   $dompdf->load_html($pr_dt);
   $dompdf->render();
   $dompdf->stream("MRA.pdf");

答案 1 :(得分:0)

DROP TABLE IF EXISTS user_circle;

CREATE TABLE user_circle 
(user_id  INT NOT NULL
,circle_id  INT NOT NULL
,user_type_id INT NOT NULL
,PRIMARY KEY(user_id,circle_id)
);

INSERT INTO user_circle VALUES
(1        ,1          ,1),
(1        ,2          ,1),
(1        ,3          ,1),
(1        ,4          ,2),
(2        ,2          ,2);

SELECT * FROM user_circle;
+---------+-----------+--------------+
| user_id | circle_id | user_type_id |
+---------+-----------+--------------+
|       1 |         1 |            1 |
|       1 |         2 |            1 |
|       1 |         3 |            1 |
|       1 |         4 |            2 |
|       2 |         2 |            2 |
+---------+-----------+--------------+

SELECT DISTINCT x.* 
           FROM user_circle x 
           LEFT 
           JOIN user_circle y 
             ON y.circle_id = x.circle_id 
            AND y.user_id <> x.user_id 
          WHERE x.user_id = 1 
            AND x.user_type_id = 1 
            AND y.user_id IS NULL;
+---------+-----------+--------------+
| user_id | circle_id | user_type_id |
+---------+-----------+--------------+
|       1 |         1 |            1 |
|       1 |         3 |            1 |
+---------+-----------+--------------+

DELETE x 
  FROM user_circle x 
  LEFT 
  JOIN user_circle y 
    ON y.circle_id = x.circle_id 
   AND y.user_id <> x.user_id 
 WHERE x.user_id = 1 
   AND x.user_type_id = 1 
   AND y.user_id IS NULL;
Query OK, 2 rows affected (0.00 sec)

SELECT * FROM user_circle;
+---------+-----------+--------------+
| user_id | circle_id | user_type_id |
+---------+-----------+--------------+
|       1 |         2 |            1 |
|       1 |         4 |            2 |
|       2 |         2 |            2 |
+---------+-----------+--------------+