2013-03-13 33 views
1

你好,我有一个表tbl_relations,它看起来像MySQL的加入为一个表的两列

----------------------------------- 
| 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_idtbl_relations.target_idid of tbl_looksup

我的问题 我需要找出那些tbl_relations who记录source_idtarget_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 

回答

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 ║ 
╚════╩═══════════╩═══════════╝ 
+1

+1看你的速度,你应该禁止前五分钟回答任何问题。 :D – hims056 2013-03-13 06:46:34

+1

@ hims056不! 'O_o'请不要':D' hehe – 2013-03-13 06:47:53

+0

@JW。它很出色。谢谢兄弟 – 2013-03-13 07:01:01

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) 
0

尝试添加此:

WHERE tbl_relations。 target_id IS NULL

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