1

你好,我有一张桌子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_relationstbl_looksup以这样的方式映射到tbl_relations.source_id并且tbl_relations.target_idid of tbl_looksup

我的问题 我需要找出那些记录在tbl_relationswhoessource_idtarget_id不存在于tbl_looksup. 这意味着 中不id存在tbl_looksup。更详细地说, tbl_relations 的第一条记录target_id = 4tbl_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
4

4 回答 4

2

为了获得您想要的结果,您需要加入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 ║
╚════╩═══════════╩═══════════╝
于 2013-03-13T06:43:28.783 回答
0
SELECT 
  tbl_relations.source_id,
  tbl_relations.target_id,
  tbl_relations.id 
FROM
  tbl_relations 
   WHERE tbl_relations.source_id not in (select id from tbl_looksup)
      OR tbl_relations.target_id not in (select id from tbl_looksup)
于 2013-03-13T06:45:00.063 回答
0

尝试添加这个:

在哪里 tbl_relations。target_id一片空白

于 2013-03-13T06:45:50.760 回答
0
SELECT tbl_relations.id FROM tbl_relations 
  LEFT JOIN tbl_looksup 
    ON tbl_looksup.id = tbl_relations.source_id OR tbl_looksup.id = tbl_relations.target_id 
  WHERE tbl_looksup.id IS NULL
于 2013-03-13T06:47:09.870 回答