【问题标题】:MYSQL - How to SELECT CASE (two tables, if not present in one, check the other)MYSQL - 如何选择案例(两个表,如果一个不存在,请检查另一个)
【发布时间】:2012-06-22 23:49:01
【问题描述】:

我拥有的是 mysql 数据库中的两个表。

一个表包含值为"example@example.com"的字段

另一张桌子没有……

我想做的是检查两个表中是否有一个值与"example@example.com" 匹配的字段。

这是我的查询不起作用:

(#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 13)

SELECT CASE WHEN
EXISTS (
    SELECT address, suburb, city, postCode, province
    FROM user_postal
    INNER JOIN user_info ON user_postal.id = user_info.id
    WHERE user_info.emailContact = 'example@example.com'
)
OR EXISTS (
    SELECT address, suburb, city, postCode, province
    FROM user_postal
    INNER JOIN user_business_info ON user_postal.id = user_business_info.id
    WHERE user_business_info.emailContact = 'example@example.com'
)

我想返回与电子邮件example@example.com 匹配的用户ID 字段address, suburb, city, postCode, province 的值。 (这可能在两个表中的任何一个中,但肯定在一个或另一个中)

谁能告诉我我哪里出了问题?任何这方面的信息将不胜感激。谢谢!

【问题讨论】:

    标签: mysql select case


    【解决方案1】:

    这个怎么样:

    SELECT address, suburb, city, postCode, province
    FROM user_postal
    INNER JOIN user_info ON user_postal.id = user_info.id
    WHERE user_info.emailContact = 'example@example.com'
    
    UNION
    
    SELECT address, suburb, city, postCode, province
    FROM user_postal
    INNER JOIN user_business_info ON user_postal.id = user_business_info.id
    WHERE user_business_info.emailContact = 'example@example.com'
    

    【讨论】:

      【解决方案2】:

      这是您要使用UNION 的地方。

      【讨论】:

      • 感谢您的意见,您能解释一下为什么我的工会在这种情况下会更好吗?我已经根据是否存在匹配来调整查询,选择 1 或 0 的情况...但是在这种情况下为什么要联合?
      【解决方案3】:
      SELECT address, suburb, city, postCode, province 
      FROM user_postal
              INNER JOIN user_business_info ON (user_postal.id = user_business_info.id AND user_info.emailContact = 'example@example.com')
                                              OR (user_postal.id = user_info.id AND user_business_info.emailContact = 'example@example.com')
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-02-21
        • 1970-01-01
        • 2022-01-17
        • 1970-01-01
        • 2018-03-20
        • 2013-01-04
        • 2020-04-04
        • 1970-01-01
        相关资源
        最近更新 更多