2012-08-14 75 views
1

我需要一些幫助,在這裏我有這個2個表:選擇..哪裏...或從2個表

table "clients" 
+------+-------------+-----------+ 
    id | email  | otherinfo| 
+------+-------------+-----------+ 
    1 |[email protected] | ..... | 
+------+-------------+-----------+ 
    2 |[email protected] | .... | 
+------+-------------+-----------+ 

table "comptes" 
+------+-------------+---------------+ 
    id | login  | id_clients | 
+------+-------------+---------------+ 
1  |  test | 1    | 
+------+-------------+---------------+ 
1  |  test2 | 2    | 
+------+-------------+---------------+ 
etc. | etc.  |  etc.. | 
+------+-------------+---------------+ 

在我的網站,當用戶箱子的賬戶,他給兩個表的信息。所以我想加入他們,像這樣

'select clients.email,comptes.login  
from clients,comptes  
where clients.email='[email protected]' 
or comptes.login ='test'; 

之前對其進行測試,如果登錄或電子郵箱存在於數據庫中,但該查詢返回空結果,我累了其他組合,但沒有放棄。所以我是誰搞亂正確的結果這裏

回答

1

你不需要一個返回兩行加入一切,看看他們是否存在。下面的查詢返回任何匹配的記錄的ID:

select c.id, 'email' as matchtype 
from clients c 
where c.email = <email> 
union all 
select c.id, 'login' as matchtype 
from comptes c 
where c.login = <login> 

這給你匹配的IDS,並告訴你在副本的出現(如果是這樣的利息)。如果你只是想要一個0或1的標誌,指定副本的存在,這樣做:

select count(*) as numdups 
from ((select c.id, 'email' as matchtype 
     from clients c 
     where c.email = <email> 
    ) 
     union all 
     (select c.id, 'login' as matchtype 
     from comptes c 
     where c.login = <login> 
    ) 
    ) t 
+0

感謝,這工作非常出色,但第二個查詢返回該錯誤「每一個派生表必須有它自己的別名」 – user1559104 2012-08-14 20:47:50

+0

@ user1559104。 。 。我不確定這是爲什麼。你有最後的「t」嗎?我檢查SQL小提琴,並且甚至在union all之前都不允許別名。 – 2012-08-14 21:08:38

+0

我沒有刪除最後的「t」,我用phpmyadmin使用mysql。無論如何,我使用第一個解決方案,謝謝 – user1559104 2012-08-14 21:14:30

1

您需要的specifica lly識別你的JOIN字段。逗號分隔的連接語法使用起來很差(IMO),並且可能會給出意想不到的結果。在你的情況下,它試圖在兩個id列上連接兩個表。因此,嘗試這種

SELECT clients.email, comptes.login 
FROM clients INNER JOIN comptes on clients.id = comptes.id_clients 
WHERE clients.email='[email protected]' OR comptes.login = 'test'; 

注意,在這種情況下,你會因爲你的WHERE子句將最終給你兩個客戶端編號1和2

0
SELECT cl.email, co.login 
FROM clients AS cl 
    INNER JOIN comptes AS co ON cl.id = co.id_clients 
WHERE cl.email = '[email protected]' OR co.login = 'test'