你好,我有一个表tbl_relations
,看起来像
-----------------------------------
| id | source_id | target_id |
-----------------------------------
| 2 | 2 | 4 |
-----------------------------------
| 3 | 5 | 7 |
-----------------------------------
| 4 | 7 | 4 |
-----------------------------------
和其他表 tbl_looksup
看起来像
------------------------------
| id | language | value |
------------------------------
| 1 | 1 | abc |
------------------------------
| 1 | 2 | abc |
------------------------------
| 2 | 1 | abc |
-------------------------------
| 2 | 2 | abc |
-------------------------------
| 5 | 1 | abc |
-------------------------------
| 5 | 2 | abc |
-------------------------------
| 7 | 1 | abc |
-------------------------------
| 7 | 1 | abc |
-------------------------------
tbl_relations
映射到 tbl_looksup
的方式是 tbl_relations.source_id
和 tbl_relations.target_id
是tbl_looksup 的 id
我的问题
我需要在 tbl_relations
中找出那些 source_id
或 target_id
不在 tbl_looksup
中的记录。这意味着 tbl_looksup
中不存在 id
。更详细地,tbl_relations 的第一条记录有 target_id = 4
,它在 tbl_looksup
中不存在。这是错误的记录。我需要找出这些记录。
到目前为止我做了什么
SELECT
tbl_relations.source_id,
tbl_relations.target_id,
tbl_relations.id,
tbl_looksup.`id` AS tblid
FROM
tbl_relations
LEFT JOIN tbl_looksup
ON tbl_relations.`source_id` != tbl_looksup.`id`
OR tbl_relations.`target_id` != tbl_looksup.`id`
GROUP BY tbl_relations.id
最佳答案
为了获得您想要的结果,您需要加入 tbl_looksup
两次,因为有两列依赖于该表。
SELECT DISTINCT a.*
FROM tbl_relations a
LEFT JOIN tbl_looksup b
ON a.source_id = b.id
LEFT JOIN tbl_looksup c
ON a.target_id = c.id
WHERE b.id IS NULL OR
c.id IS NULL
要进一步了解有关联接的更多信息,请访问以下链接:
输出
╔════╦═══════════╦═══════════╗
║ ID ║ SOURCE_ID ║ TARGET_ID ║
╠════╬═══════════╬═══════════╣
║ 2 ║ 2 ║ 4 ║
║ 4 ║ 7 ║ 4 ║
╚════╩═══════════╩═══════════╝
关于mysql连接一个表的两列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15378610/