Mysql 根据连接拆分列值 table
Mysql split the column values based on the joining table
我需要一个查询来根据倍数 table 查找计数。请检查以下详细信息
我有 3 个 table,因为 table_1、table_2、table_3 和 table_1 是主要的 table,以及其他2 继承自初级。这些 table 具有 profile_id 列的公共值。检查此示例查询计数器
SELECT COUNT(profile_id)
from table_1
WHERE profile_id IN (SELECT profile_id FROM table_2)
以上查询returns基于table_2 profile id
的计数。但我需要分别查询所有 table,如下所示
SELECT COUNT(profile_id) as table_2count,
COUNT(profile_id) as table_3count
FROM table_1 WHERE (the two condition)
在上面的查询中,table_2count 基于 table_2 个配置文件,table_3count 将基于 table_3。我如何将这些值合并到单个查询中。请提出一些方法来找出计数值。
您可以使用 2 个子查询来实现:
SELECT
t1.*, -- get all data from t1 + two counts from t2 and t3
(SELECT COUNT(t2.profile_id)
FROM table_2 t2
WHERE t2.profile_id = t1.profile_id) as count2,
(SELECT COUNT(t3.profile_id)
FROM table_3 t3
WHERE t3.profile_id = t1.profile_id) as count3
FROM table_1 t1
WHERE <your conditions for table_1 go here>
如果 profile_id
在 table_1
中是唯一的并且你在 table_2
和 table_3
中有外键,你真的不需要加入 [=20] =],你需要的是这样的东西。
SELECT
(SELECT COUNT(distinct profile_id) FROM table_2) table_2count,
(SELECT COUNT(distinct profile_id) FROM table_3) table_3count
如果你真的需要一个连接或者没有定义外键,你可以使用这个
SELECT
COUNT(distinct t2.profile_id) table_2count,
COUNT(distinct t3.profile_id) table_3count
FROM table_1 t1
LEFT JOIN table_2 t2 on t1.profile_id = t2.profile_id
LEFT JOIN table_3 t3 on t1.profile_id = t3.profile_id
我需要一个查询来根据倍数 table 查找计数。请检查以下详细信息
我有 3 个 table,因为 table_1、table_2、table_3 和 table_1 是主要的 table,以及其他2 继承自初级。这些 table 具有 profile_id 列的公共值。检查此示例查询计数器
SELECT COUNT(profile_id)
from table_1
WHERE profile_id IN (SELECT profile_id FROM table_2)
以上查询returns基于table_2 profile id
的计数。但我需要分别查询所有 table,如下所示
SELECT COUNT(profile_id) as table_2count,
COUNT(profile_id) as table_3count
FROM table_1 WHERE (the two condition)
在上面的查询中,table_2count 基于 table_2 个配置文件,table_3count 将基于 table_3。我如何将这些值合并到单个查询中。请提出一些方法来找出计数值。
您可以使用 2 个子查询来实现:
SELECT
t1.*, -- get all data from t1 + two counts from t2 and t3
(SELECT COUNT(t2.profile_id)
FROM table_2 t2
WHERE t2.profile_id = t1.profile_id) as count2,
(SELECT COUNT(t3.profile_id)
FROM table_3 t3
WHERE t3.profile_id = t1.profile_id) as count3
FROM table_1 t1
WHERE <your conditions for table_1 go here>
如果 profile_id
在 table_1
中是唯一的并且你在 table_2
和 table_3
中有外键,你真的不需要加入 [=20] =],你需要的是这样的东西。
SELECT
(SELECT COUNT(distinct profile_id) FROM table_2) table_2count,
(SELECT COUNT(distinct profile_id) FROM table_3) table_3count
如果你真的需要一个连接或者没有定义外键,你可以使用这个
SELECT
COUNT(distinct t2.profile_id) table_2count,
COUNT(distinct t3.profile_id) table_3count
FROM table_1 t1
LEFT JOIN table_2 t2 on t1.profile_id = t2.profile_id
LEFT JOIN table_3 t3 on t1.profile_id = t3.profile_id