MYSQL - 如何从两个表中查找结果?

时间:2015-09-18 05:58:51

标签: mysql sql select sql-like

我对mysql不满意,所以需要知道如何从两个表中找到结果。

我们说我有两张桌子:

品牌表:

Id  Email           Password
--  -----           --------
1   kris@gmail.com  12345678

Facebook表格:

Id  Email               Password
--  -----               --------
1   calbares@gmail.com  12345678

现在,我想从这两个表中找到此电子邮件地址calbares@gmail.com,并希望获得电子邮件&来自结果的密码。

任何想法如何做到这一点?

感谢。

4 个答案:

答案 0 :(得分:1)

要做,请尝试这个

Select * from Brand where Email = '$email';

UNION ALL

Select * from Facebook where Email = '$email';

答案 1 :(得分:1)

SELECT * FROM brand_table
union
select * from facebook_table

UNION会带来不同的记录。

如果您使用union all,它也会带来重复。

在你的情况下:

SELECT * FROM brand_table where email ='calbares@gmail.com'
union all
select * from facebook_table where email ='calbares@gmail.com'

答案 2 :(得分:0)

为了更实用,您可以在电子邮件中使用变量:

SET @email='calbares@gmail.com'

SELECT 'Brand' AS Platform, Email, Password
FROM Brand WHERE Email=@email

UNION ALL

SELECT 'Facebook', Email, Password
FROM Facebook WHERE Email=@email

或者创建一个函数/过程:

CREATE PROCEDURE find_Passwords(IN emailin varchar(255))
BEGIN
SELECT 'Brand' AS Platform, Email, Password
    FROM Brand WHERE Email=emailin

    UNION ALL

    SELECT 'Facebook', Email, Password
    FROM Facebook WHERE Email=emailin
END

您可以致电:

CALL find_Passwords('calbares@gmail.com')

答案 3 :(得分:0)

这两个表中的电子邮件地址是一样的吗?

如果是,请使用以下命令:

"SELECT brand.password AS brand_pw, facebbok.password AS fb_password FROM brand JOIN facebook ON facebook.email = 'calbares@gmail.com' WHERE brand.email = 'calbares@gmail.com'"

结果你得到两个值:brand_pw和fb_password。因为您知道该电子邮件,所以无需从表中收集它。

但如果您还想收到电子邮件,只需在SELECT后添加以下内容:brand.email AS brand_mail,facebook.email AS fb_email

所以完整的命令应如下所示:

"SELECT brand.password AS brand_pw, brand.email AS brand_mail, facebook.email AS fb_email, facebbok.password AS fb_password FROM brand JOIN facebook ON facebook.email = 'calbares@gmail.com' WHERE brand.email = 'calbares@gmail.com'"

所以你得到4个值。