从两个表中的同一列中选择唯一值

时间:2016-06-23 10:20:40

标签: mysql sql duplicates unique

我只是在玩SQL并希望获得以下结果 我有以下表格:

TABLE_1   ID   NAME
          1    CAR
          2    ANIMAL
          5    ROCK

TABLE_2   ID   NAME
          1    GRASS
          2    ROCKET
          3    STONE
          4    DOG

我希望我的查询从两个表中返回唯一的ID值:

ID
3
4
5

我尝试过使用DISTINCT和FULL OUTER JOINS,但没有成功。 任何帮助将不胜感激。

6 个答案:

答案 0 :(得分:6)

您可以使用UNION ALL,对其进行分组并使用HAVING子句:

SELECT ID FROM (
    SELECT ID FROM Table_1
    UNION ALL
    SELECT ID FROM Table_2)
GROUP BY ID
HAVING COUNT(*) = 1

答案 1 :(得分:2)

试试这个:

SELECT ID
FROM (
  SELECT ID
  FROM TABLE_1

  UNION ALL

  SELECT ID
  FROM TABLE_2) AS t
GROUP BY ID
HAVING COUNT(*) = 1

答案 2 :(得分:2)

试试这个;)

class ClearListener implements ActionListener {

    public void actionPerformed(ActionEvent e) {
        Object selected = list.getSelectedValue();
        try {
            removeIndexInterval();
            deleteFiles(selected);
        } catch (IOException e1) {
            // TODO Auto-generated catch block
                e1.printStackTrace();
            }   
        }
    }

    public void removeIndexInterval() {
        DefaultListModel dlm = (DefaultListModel) this.list.getModel();
        if (this.list.getSelectedIndices().length > 0) {
            int[] tmp = this.list.getSelectedIndices();
            int[] selectedIndices = this.list.getSelectedIndices();
            for (int i = tmp.length - 1; i >= 0; i--) {
                selectedIndices = this.list.getSelectedIndices();
                dlm.removeElementAt(selectedIndices[i]);
            } // end-for
        } // end-i
    }

    public void deleteFiles(Object objects) throws IOException {
        File[] files = ((File) objects).listFiles();
        for (File file : files) {
            if (file.isFile()) {
                String fileName = file.getName();
                boolean del = file.delete();
                System.out.println(fileName + " : Deleted ? " + del);
            } else if (file.isDirectory()) {
                deleteFiles(file);
            }
        }
    }
}

SQLFiddle DEMO

答案 3 :(得分:1)

&#160;&#160;Whatever<LineBreak />More Text

答案 4 :(得分:0)

使用UNION手动构建交叉点。如果两个表中都有一些独特的字段,例如,这很简单,例如ID:

SELECT id FROM Table 1
WHERE id NOT IN (SELECT id FROM Table 2)

UNION

SELECT id FROM Table 2
WHERE id NOT IN (SELECT id FROM Table 1)

答案 5 :(得分:-1)

SELECT table_1.id
FROM   table_1
WHERE  table_1.id NOT IN (SELECT table_2.id FROM table_2)
UNION
SELECT table_2.id
FROM   table_2
WHERE  table_2.id NOT IN (SELECT table_1.id FROM table_1)