[英]MySQL How can I make query that gets info from my junction table as well as data that is not in that junction
[英]MySQL: How can I delete two rows in a junction table based on a specific ID?
我有一個 Mysql 聯結表 user_connections,它將用戶表映射到以下列:user_from 和 user_to,它們都是用戶表中的外鍵。 user_from 和 user_to 都是主鍵,因此像 (1,2) 和 (1,2) 這樣的 parttern 永遠不會重復。
用戶連接表。
create table user_connections (
user_from int,
user_to int,
primary key(user_from, user_to)
);
insert into user_connections(user_from, user_to) values(1, 2);
insert into user_connections(user_from, user_to) values(2, 1);
insert into user_connections(user_from, user_to) values(67, 1);
insert into user_connections(user_from, user_to) values(68, 1);
insert into user_connections(user_from, user_to) values(69, 1);
insert into user_connections(user_from, user_to) values(70, 1);
插入后的樣子
查詢 #1
select * from user_connections;
user_from | user_to |
---|---|
1個 | 2個 |
2個 | 1個 |
67 | 1個 |
68 | 1個 |
69 | 1個 |
70 | 1個 |
我的問題是如何使用一個基於 ID 2 的查詢刪除模式 (1,2) 和 (2,1)。此外,如果我讓我們說另一種模式,如 (67, 2) 和 (2, 67),如何我會刪除那些模式嗎?
先感謝您。
我得到了解決方案。 我只需要使用 WHERE IN 如下:
DELETE FROM user_connections
WHERE (user_from, user_to) in ((1, 2), (2, 1))
假設您有一個用戶表,其 ID 鏈接到您在此處描述的 2 列。 像這樣的請求可以完成這項工作:
DELETE uc
FROM user_connections uc
INNER JOIN user u
ON u.id = uc.user_from
OR u.id = uc.user_to
WHERE u.id = 2;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.