duanlinma5885 2016-06-22 08:55
浏览 100
已采纳

mysql查询从两个表中选择不同的值,并在两个表中使用sum值计数

I have two tables in db

1- i want to select distinct value from 2 tables

2- i want to print the number of each value

Ex: if i have on t1

t1
--------------
a

a

a

b

t2:

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/>";
}
  • 写回答

2条回答 默认 最新

  • doudi8525 2016-06-22 09:03
    关注

    You need UNION ALL instead of UNION. That way you merge the values from 2 tables into 1 virtual table. Then you can count the number of individual values using GROUP BY clause. Example:

    select f, COUNT(f) as countf FROM
    (select t1.f from t1 union all select t2.f from t2) t
    GROUP BY f
    

    SQL Fiddle

    In PHP you can then use $res['countf'] to print the count

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化