如何从子查询中的不同表中获取特定行数
我知道这是可能的,但我没有足够的经验来知道如何进行子查询。
情况是这样的:
Table 1:
+--------------------+--------------------+
| v_id | v_name |
+--------------------+--------------------+
| 1 | v_name1 |
+--------------------+--------------------+
| etc...
Table 2:
+--------------------+--------------------+
| a_id | a_name |
+--------------------+--------------------+
| 1 | a_name1 |
+--------------------+--------------------+
| etc...
Table 3:
+--------------------+--------------------+
| v_id | a_id |
+--------------------+--------------------+
| 1 | 1 |
+--------------------+--------------------+
| 1 | 2 |
+--------------------+--------------------+
| 1 | 3 |
+--------------------+--------------------+
| 2 | 3 |
+--------------------+--------------------+
| 2 | 1 |
+--------------------+--------------------+
我相信这是一种很常见的情况。
因此,我在表 1
和表 2
中有独特的条目。
我想要SELECT
来自Table 1
的所有行并获取(作为每行的最后一个单元格)具有Table 3
中相应值的行数代码>.
这是行不通的:
SELECT t1.* , COUNT(SELECT t3.* FROM `table_3` t3 WHERE t3.v_id = t1.v_id) as entries
FROM `table 1` t1;
我确信这里的专家会告诉我这都是错误的,但坦率地说,这就是我正在寻找的(以及一些有用的解决方案!)。 ;)
I know it's possible, but I'm not experienced enough to know how to do subqueries.
Here's the situation:
Table 1:
+--------------------+--------------------+
| v_id | v_name |
+--------------------+--------------------+
| 1 | v_name1 |
+--------------------+--------------------+
| etc...
Table 2:
+--------------------+--------------------+
| a_id | a_name |
+--------------------+--------------------+
| 1 | a_name1 |
+--------------------+--------------------+
| etc...
Table 3:
+--------------------+--------------------+
| v_id | a_id |
+--------------------+--------------------+
| 1 | 1 |
+--------------------+--------------------+
| 1 | 2 |
+--------------------+--------------------+
| 1 | 3 |
+--------------------+--------------------+
| 2 | 3 |
+--------------------+--------------------+
| 2 | 1 |
+--------------------+--------------------+
I believe this is a quite common situation.
So, I have unique entries in Table 1
and Table 2
.
I want to SELECT
all rows from Table 1
and get (as the last cell in each row) the number of rows with the corresponding value in Table 3
.
This doesn't work:
SELECT t1.* , COUNT(SELECT t3.* FROM `table_3` t3 WHERE t3.v_id = t1.v_id) as entries
FROM `table 1` t1;
I'm sure I'm gonna be told off by experts here that it's all wrong, but frankly, that's what I'm looking for (and some helpful solution as well!). ;)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用:
Use: