mysql - 如何将这两个 SQL 语句合并为一个?

标签 mysql sql mariadb

我写了并且想结合这 2 个 sql,一个基于另一个的结果。我检查了 this post , 但看起来它不是基于结果的。我怎样才能实现它?

第一个sql:

SELECT
    `potential`.*,
    `customer`.`ID` as 'FID_customer'
FROM
    `os_potential` as `potential`,
    `os_customer` as `customer`
WHERE `potential`.`FID_author` = :randomID
      AND `potential`.`converted` = 1
      AND `potential`.`street` = `customer`.`street`
      AND `potential`.`zip` = `customer`.`zip`
      AND `potential`.`city` = `customer`.`city`;

第二条语句:

SELECT
    sum(`order`.`price_customer`) as 'Summe'
FROM
    `os_order` as `order`,
    `RESUTS_FROM_PREVIOUS_SQL_STATEMENT` as `results`
WHERE `order`.`FID_status` = 10
      AND `results`.`FID_customer` = `order`.`FID_customer`;

我想从第一个 sql 中获取所有内容 + 从第二个 sql 中获取“Summe”。

表格

1.潜力:

+----+------------+-----------+--------+-----+------+
| ID | FID_author | converted | street | zip | city |
+----+------------+-----------+--------+-----+------+

2.客户:

+----+--------+-----+------+
| ID | street | zip | city |
+----+--------+-----+------+

3.订单:

+----+--------------+----------------+
| ID | FID_customer | price_customer |
+----+--------------+----------------+

最佳答案

SELECT p.*
     , c.ID FID_customer
     , o.summe
  FROM os_potential p
  JOIN os_customer c
    ON c.street = p.street 
   AND c.zip = p.zip 
   AND c.city = p.city 
  JOIN 
     ( SELECT FID_customer
            , SUM(price_customer) Summe
         FROM os_order 
        WHERE FID_status = 10
        GROUP
           BY FID_customer
     ) o
    ON o.FID_customer = c.ID
 WHERE p.FID_author = :randomID 
   AND p.converted = 1
   ;

关于mysql - 如何将这两个 SQL 语句合并为一个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39349104/

相关文章:

Mysql VS MariaDb 相同的查询性能

mysql - 查询同一日期之间的数据

php - 在 while 循环中组合两个 SQL 查询

php - mySQL 查询中的更新不起作用?

MYSQL SELECT 最近的 id 和 ORDER BY

sql - DateAdd 列导致溢出

mysql - 如何在 Dockerfile 'CMD ["mysqld"]' 之后运行脚本 shell?

mysql - 你能在 MySql 中将行转换为 json 吗?

sql - 在 Oracle 10 中删除锁

sql - 实际类型的值不正确地比较