我需要一些帮助,我有这两张桌子:
table "clients"
+------+-------------+-----------+
id | email | otherinfo|
+------+-------------+-----------+
1 |test@ts.ts | ..... |
+------+-------------+-----------+
2 |test2@.ts.ts | .... |
+------+-------------+-----------+
table "comptes"
+------+-------------+---------------+
id | login | id_clients |
+------+-------------+---------------+
1 | test | 1 |
+------+-------------+---------------+
1 | test2 | 2 |
+------+-------------+---------------+
etc. | etc. | etc.. |
+------+-------------+---------------+
在我的网站上,当用户创建一个帐户时,他会提供两个表的信息。所以我想在添加它们之前测试数据库中是否存在LOGIN或EMAIL,如下所示
'select clients.email,comptes.login
from clients,comptes
where clients.email='test2@.ts.ts'
or comptes.login ='test';
但是这个查询返回空结果,我厌倦了其他组合,但没有给出正确的结果。所以我在这里弄乱了什么
答案 0 :(得分:4)
您需要使用JOIN告诉mysql数据的相关性:http://dev.mysql.com/doc/refman/5.6/en/join.html
例如:
SELECT clients.email, comptes.login
FROM clients
JOIN comptes ON clients.id = comptest.id_clients
WHERE clients.email='test2@.ts.ts'
OR comptes.login ='test';
答案 1 :(得分:1)
您需要专门识别您的JOIN字段。逗号分隔的连接语法使用起来很差(IMO)并且可能会产生意外结果。在你的情况下,它试图加入两个id列上的两个表。所以试试这个
SELECT clients.email, comptes.login
FROM clients INNER JOIN comptes on clients.id = comptes.id_clients
WHERE clients.email='test2@.ts.ts' OR comptes.login = 'test';
请注意,在这种情况下,您将返回两行,因为您的WHERE子句将最终为您提供客户端ID 1和2。
答案 2 :(得分: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>
这为您提供了匹配的ID,并告诉您重复项的显示位置(如果感兴趣的话)。如果您只想要一个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
答案 3 :(得分:0)
SELECT cl.email, co.login
FROM clients AS cl
INNER JOIN comptes AS co ON cl.id = co.id_clients
WHERE cl.email = 'test2@.ts.ts' OR co.login = 'test'