我有两张桌子:
表a
+----------+------------+------------+
|session_id| product_id | orders |
+----------+------------+------------+
| 1 | 11 | 0 |
| 1 | 22 | 2 |
| 1 | 34 | 1 |
| 2 | 11 | 0 |
| 3 | 43 | 0 |
| 3 | 11 | 1 |
+----------+------------+------------+
表b:
+-----------+--------------+
|product_id |category_id |
+-----------+--------------+
| 11 | 100 |
| 12 | 101 |
| 34 | 102 |
| 22 | 103 |
| 43 | 104 |
| 13 | 105 |
+-----------+--------------+
我想要的是一张表格,其中包含每个category_id
中有session_id
个session_id
以及+-----------+--------------------+--------+
|session_id | count(category_id) | orders |
+-----------+--------------------+--------+
| 1 | 3 | 3 |
| 2 | 1 | 0 |
| 3 | 2 | 1 |
+-----------+--------------------+--------+
select a.session_id,count(b.category_id),sum(a.orders) from a
join table b
on a.product_id = b.product id
我试过了:
Connection c =DriverManager.getConnection("jdbc:mysql"+"://"+host+":"+port+"/"+db,"root","pass");
这个查询对吗?
请帮帮我。我是初学者
答案 0 :(得分:2)
当然你没有加入桌子,然后与你想要的领域分组。
SELECT a.Session_ID, Count(Category_ID) CategoryCount, SUM(Orders) NumberOfOrders
FROM a
LEFT OUTER JOIN b
ON a.Product_ID = b. Product ID
GROUP BY a.Session_ID
就个人而言,由于我没有使用LEft外部联接的数据结构的任何信息,因为如果product_id没有类别,则不会显示该产品的结果。
(除非每个产品都有一个类别,或者用户只需要具有类别的产品,否则您必须使用INNER JOIN
)
答案 1 :(得分:2)
只需使用左连接即可显示表A中的所有结果 通过仅使用它的show,结果只存在于两个表中。
SELECT a.session_id,COUNT(b.category_id),SUM(a.orders) FROM a
LEFT JOIN b
ON a.product_id = b.product_id GROUP BY a.`session_id`
答案 2 :(得分:2)
I tried with 2 methods
1)...SELECT a.session_id,COUNT(b.category_id),SUM(a.orders) FROM #a a
LEFT JOIN #b b
ON a.product_id = b.product_id GROUP BY a.session_id
GROUP BY a.Session_ID
2...) SELECT D.SESSION_ID,COUNT(CATEGORY_ID),SUM(D.ORDERS) FROM #A D
OUTER APPLY
(
SELECT CATEGORY_ID,PRODUCT_ID FROM #B B
WHERE D.PRODUCT_ID = B.PRODUCT_ID
) A
GROUP BY D.SESSION_ID
GO