2014-02-28 33 views
0

我有一個在mysql中有bus_id和cus_id的表。我想從表中得到B108作爲返回值,因爲我希望結果的值不等於C108,而C108也有B109。所以我也不想第3行的值。我想只得到第2行作爲我的結果。請向我推薦這些表的選擇查詢。如何從表中獲取唯一數據?

我的表是:

enter image description here

回答

0

我沒有測試過,但是這樣的事情可能工作

SELECT bus_id FROM表WHERE bus_id NOT IN(SELECT bus_id FROM table WHERE cus_id = C108)

+0

安德魯和我有種重疊 –

+0

這就是爲什麼我沒有發佈...唷.. stackoverflowians是該死的快... –

0

試試這個:

select bus_id from table where bus_id not in (select bus_id from table where cus_id='c108') 
0

您可以使用mysql DISTINCT函數與您的條件。

例如。 從table_name中選擇distinct(column_name)WHERE cus_id <>'C108'AND bus_id <>'B109';

1

您可以單獨使用組表並檢測每個列的重複值,然後使用這些值篩選表。

select * from table 
    where cus_id not in 
    (select cus_id from table 
    group by cus_id 
    having count(*) > 1) 
    and 
    bus_id not in 
    (select bus_id from table 
    group by bus_id 
    having count(*) > 1) 
0

嘗試此查詢

CREATE TABLE BUS 
    (`cb_id` int, `bus_id` varchar(4), `cus_id` varchar(4)) 
; 

INSERT INTO BUS 
    (`cb_id`, `bus_id`, `cus_id`) 
VALUES 
    (1, 'B101', 'C108'), 
    (2, 'B108', 'C101'), 
    (3, 'B109', 'C102'), 
    (24, 'B109', 'C108') 
; 




SELECT 
    * 
FROM BUS B 
WHERE cus_id<>'C108' 
AND NOT EXISTS(SELECT * FROM BUS B1 
     WHERE 
      B1.BUS_ID=B.BUS_ID 
     AND B1.cus_id='C108') 
0

如果你的意思是忽略誰在列bus_idcus_id 2個或多個數據記錄,也許你可以使用此查詢:

select * from buscus a where 
    a.bus_id not in (select b.bus_id from (select count(bus_id) as cb, bus_id FROM BusCus group by bus_id) b where b.cb > 1) 
and 
    a.cus_id not in (select c.cus_id from (select count(cus_id) as cc, cus_id FROM BusCus group by cus_id) c where c.cc > 1)