在Wordpress的SQL语句上遇到一些问题。创建了一个自定义字段" member_name"在key = member_name下的order3中保存。我需要创建一个报告,显示每个member_name的数量的和(在key =" _qty"下保存的order2)。
TABLES:
order1 - order1_id, order3_id
order2 - order2_id, key, value
order3 - order3_id, key, value
示例:
order1
order1_id - order3_id
2 - 292
3 - 292
4 - 281
order2
order2_id - key - value
2 - '_qty' - 1
3 - '_qty' - 2
4 - '_qty' - 1
order3
order3_id - key - value
292 - 'member_name' - John
292 - 'member_name' - John
281 - 'member_name' - Bill
期望的结果:
John 3
Bill 2
以下是我正在使用的内容:
SELECT order3.value, a.member_count
FROM ((order3
INNER JOIN order3(select value, sum(*) as member_count
FROM order2
GROUP BY value
WHERE order2.value='_qty') a
ON order3.order3_id=order1.order1_id)
INNER JOIN order2
ON order2.order2_id=order1.order1_id)
GROUP BY a.member_count
WHERE order3.key="member_name";
答案 0 :(得分:0)
尝试以下查询。它首先获得每个qty
的总order3_id
值。然后,从order3
表中查找名称。
SELECT DISTINCT
o3.value,
totals.total_qty
FROM order3 o3
INNER JOIN
(
SELECT
o1.order3_id order3_id,
sum(o2.value) total_qty
FROM order2 o2
INNER JOIN order1 o1 ON o2.order2_id = o1.order1_id AND o2.key = '_qty'
GROUP BY o1.order3_id
) totals
ON o3.order3_id = totals.order3_id AND o3.key = 'member_name';
您可以在order3表中按名称分组。但是,如果2 order3_id具有相同的名称,您将得到意外的结果。