如何在连接表中找到没有匹配值的记录

时间:2017-09-21 16:35:59

标签: sql sqlite

我有这些SQL语句:

SELECT COUNT(*) FROM Phrase   -- Returns 660 rows

SELECT COUNT(*) FROM Score    -- Returns 660 rows

SELECT count(*)               -- Returns 660 rows
FROM Score AS S
JOIN Phrase AS P ON S.PhraseId = P.PhraseId

SELECT count(*)               -- Returns 658 rows         
FROM Score AS S
JOIN Phrase AS P ON S.PhraseId = P.PhraseId
JOIN Category AS C ON P.CategoryId = C.Id

我正在尝试弄清楚数据库中出了什么问题,并希望得到一些关于如何找到记录的短语的建议,其中一个短语的categoryId不在表中

4 个答案:

答案 0 :(得分:2)

使用 @Override public void onServicesDiscovered(BluetoothGatt gatt, int status) { if (status == BluetoothGatt.GATT_SUCCESS) { mServicesReadyBluetoothDeviceMap.clear(); for(BluetoothDevice bluetoothDevice : gatt.getConnectedDevices()) { mServicesReadyBluetoothDeviceMap.put(bluetoothDevice.getAddress(), bluetoothDevice); } IBLEComListener comListener = A35BLEManager.getBLEComListener(); if(comListener != null) { comListener.onBLEDeviceServicesReady(gatt.getDevice()); } } else { A35Log.w(TAG, "onServicesDiscovered received: " + status); } } NOT EXISTS表格中找到此类ID。

Phrase

另一个解决方案是使用 SELECT * FROM Phrase AS P WHERE NOT EXISTS (SELECT 1 FROM Category WHERE P.CategoryId = C.Id) 但是你必须更加小心可能的NULL

NOT IN

答案 1 :(得分:1)

我猜你有2个短语记录,其中CategoryId = NULL,假设短语和类别之间存在参照完整性约束。

无论如何,这应该列出这两个短语记录:

// try this...
Model::create($request->except('created_at', 'updated_at', 'deleted_at'));

答案 2 :(得分:1)

使用外部联接:

从匹配的分数和词组返回所有记录。包含匹配的类别中的行。然后排除所有在类别上匹配的内容,从分数/短语中得到2条与类别不匹配的记录。

{{1}}

效率不高,不存在/不存在,但为返回的列提供了更大的灵活性。

答案 3 :(得分:1)

use可以使用嵌套子查询来获取此

select count(*)
from score as S
where phraseId in 
(select phraseId
    from Phrase
    where phaseId not in (select phraseId from category);