【问题标题】:Python SQL - two left joinsPython SQL - 两个左连接
【发布时间】:2020-03-27 13:47:52
【问题描述】:

我在 Python 的 SQL 方面遇到了一些问题,希望您能帮助我 - 我正在尝试从 wordpress/woocommerce 检索一些数据。

我的代码:

    cursor.execute("
    SELECT t1.ID, t1.post_date, t2.meta_value AS first_name, t3.meta_value AS last_name
    FROM test_posts t1 
    LEFT JOIN test_postmeta t2 
    ON t1.ID = t2.post_id 
    WHERE t2.meta_key = '_billing_first_name' and t2.post_id = t1.ID 
    LEFT JOIN test_postmeta t3 
    ON t1.ID = t3.post_id 
    WHERE t3.meta_key = '_billing_last_name' and t3.post_id = t1.ID 
    GROUP BY t1.ID 
    ORDER BY t1.post_date DESC LIMIT 20")

我收到以下错误:

    mysql.connector.errors.ProgrammingError: 1064 (42000): 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 'LEFT JOIN test_postmeta t3 ON t1.ID = t3.post_id WHERE t3.meta_key = '_billing' at line 1

我做错了什么?

提前致谢。

【问题讨论】:

  • JOINFROM 子句中的运算符。 WHEREFROM 子句之后的子句。
  • 谢谢戈登!这是有道理的,我编辑了我的 SQL 并且它有效。谢谢。有谁知道我是否必须自己回答我的问题,或者这将如何运作?

标签: python mysql sql woocommerce mysql-connector-python


【解决方案1】:

在 GROUP BY 之前应该只有 1 个 WHERE 子句。
但由于您使用 LEFT 连接,因此在 right 表上设置一个条件,例如 t2.meta_key = '_billing_first_name',您会得到一个 INNER 连接,因为您拒绝不匹配的行。
所以在 ON 子句中设置所有条件:

cursor.execute("
SELECT t1.ID, t1.post_date, t2.meta_value AS first_name, t3.meta_value AS last_name
FROM test_posts t1 
LEFT JOIN test_postmeta t2 
ON t1.ID = t2.post_id AND t2.meta_key = '_billing_first_name'
LEFT JOIN test_postmeta t3 
ON t1.ID = t3.post_id AND t3.meta_key = '_billing_last_name'
GROUP BY t1.ID 
ORDER BY t1.post_date DESC LIMIT 20")

虽然这个查询对于 MySql 可能在语法上是正确的,但使用 GROUP BY 没有意义,因为您不进行任何聚合。

【讨论】:

    【解决方案2】:

    您的SQL 语法不正确。试试这个:

      cursor.execute("
        SELECT t1.ID, t1.post_date, t2.meta_value AS first_name, t3.meta_value AS last_name
        FROM test_posts t1 
        LEFT JOIN test_postmeta t2 ON t1.ID = t2.post_id 
        LEFT JOIN test_postmeta t3  ON t1.ID = t3.post_id 
        WHERE t3.meta_key = '_billing_last_name' and t2.meta_key = '_billing_first_name'
        GROUP BY t1.ID 
        ORDER BY t1.post_date DESC LIMIT 20")
    

    关于SQL JoinsWHERE 语句可能值得阅读。

    【讨论】:

      猜你喜欢
      • 2019-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多