[英]mysql query select distinct value from two table with the count of sum value in two table
I have two tables in db 我在数据库中有两个表
1- i want to select distinct value from 2 tables 1-我想从2个表中选择不同的值
2- i want to print the number of each value 2-我要打印每个值的编号
Ex: if i have on t1 例如:如果我在t1
t1
--------------
a
a
a
b
t2: 2:
t2
--------------
a
b
c
the result will be: 结果将是:
a (4)
b (2)
c (1)
i try this but it not what i want 我尝试这个,但不是我想要的
$sql=mysqli_query($conn,"select db_shopname from tbl_order UNION
SELECT db_shopname FROM tbl_item order by db_shopname asc")
or die(mysqli_error($conn));
$count=mysqli_num_rows($sql);
while($res=mysqli_fetch_array($sql)){
echo $res['db_shopname'];echo $count ;echo"<br/>";
}
You need UNION ALL
instead of UNION
. 您需要UNION ALL
而不是UNION
。 That way you merge the values from 2 tables into 1 virtual table. 这样,您可以将2个表中的值合并到1个虚拟表中。 Then you can count the number of individual values using GROUP BY
clause. 然后,您可以使用GROUP BY
子句计算单个值的数量。 Example: 例:
select f, COUNT(f) as countf FROM
(select t1.f from t1 union all select t2.f from t2) t
GROUP BY f
In PHP you can then use $res['countf']
to print the count 在PHP中,您可以使用$res['countf']
打印计数
try this one : 试试这个:
select a.t1,count(a.t1) as cnt from(select t1 from t1 UNION all select t2 as t1 from t2 )a group by a.t1 从a.t1中选择a.t1,count(a.t1)作为cnt from(从t1中选择t1 UNION全部从t2中选择t2作为t1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.