mysql - 具有多个连接的 MySQL 中的复杂查询

标签 mysql

一直在尝试(未成功)编写具有多个连接的查询,这就是我现在向您寻求帮助的原因。

表结构:

  • 有很多 child 和很多车的 parent
  • 一个只有一个 parent 和很多车的 child
  • 一辆要么有一个 parent 或一个 child 的汽车。

SQL Tables
(来源:zxq.net)

我正在尝试做的事情:

我正在尝试找出每个 parent 的汽车总值(value)。 ( parent “拥有”他 child 的汽车,所以 child 汽车的值(value)总和应该加到 parent 汽车值(value)的总和上)。

例如,我希望我的查询返回:

  • 如果 Thomas 有一辆值(value) 5000 的汽车,一个拥有两辆车的 child 也值 5000,则 thomas 的总值(value)为 5000 + 5000 * 2 = 15000。

  • 如果约翰有两辆值(value) 2000 元的汽车,以及两个 child ,每人有两辆值(value) 2000 元的汽车,则约翰的总值(value)为:2000 * 2 + 2000 * 2 + 2000 * 2 = 12000。

简而言之:

name   | total
--------------
Thomas | 15000
John   | 12000

到目前为止我有:

SELECT p.name,
SUM(IFNULL(carparent.price, 0)+IFNULL(carchild.price, 0)) total
FROM parent p 

# first get the childrens cars
INNER JOIN child c ON c.parent_id = p.id
INNER JOIN car carchild ON carchild.child_id = c.id

# now get the parents cars
LEFT JOIN car carparent ON carparent.parent_id = p.id

GROUP BY p.name
ORDER BY total DESC

当 parent 有多个 child 时返回奇怪的结果......我想我对所有的 JOINS 感到困惑......

无论如何,如果有人能指出我正确的方向,我将不胜感激:)

非常感谢,

最佳答案

我试过按照前面所述制作您的数据库。

这是我的解决方案。

select 
Name,
(select sum(price) 
    from car 
    where car.Parent_id=parent.id) as `Value Parent Car(s)`, 
(select sum(price) 
    from car 
    left join child 
    on car.child_id=child.id 
    where child.parent_id=parent.id) as `Value of Child car(s)`
from parent

或者获取总数

select 
id, 
Name,
((select sum(price) 
    from car 
    where car.Parent_id=parent.id) +
(select sum(price) 
    from car 
    left join child 
    on car.child_id=child.id 
    where child.parent_id=parent.id)) as `Total Value car(s)`
from parent

我确信可以找到更好的结构...例如,汽车由一个人拥有,一个人可以是 parent 、 child 或两者...

关于mysql - 具有多个连接的 MySQL 中的复杂查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23678139/

相关文章:

php - 将wordpress表单输入sql

mysql - 如何编写查询以在日期范围内显示 'breaks'?

Python MySQLdb - 我必须关闭游标和连接吗?

mysql - 当前不支持同一事务内的多个同时连接或具有不同连接字符串的连接

python - tkinter Treeview 将 mysql 数据放入一列

javascript - PHP 表单执行后的导航

c# - 循环读取 XML 文件

javascript - JQuery 循环(php + sql)

mysql 删除仅在文本字段开头的\r\n 吗?

MySQL 不返回相同的结果