2012-08-14 76 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'