簡體   English   中英

mysql查詢從兩個表中選擇不同的值,並在兩個表中求和

[英]mysql query select distinct value from two table with the count of sum value in two table

我在數據庫中有兩個表

1-我想從2個表中選擇不同的值

2-我要打印每個值的編號

例如:如果我在t1

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

a

a

b

2:

t2
--------------
a

b

c

結果將是:

a (4)

b (2)

c (1)

我嘗試這個,但不是我想要的

$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/>";
}

您需要UNION ALL而不是UNION 這樣,您可以將2個表中的值合並到1個虛擬表中。 然后,您可以使用GROUP BY子句計算單個值的數量。 例:

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

SQL小提琴

在PHP中,您可以使用$res['countf']打印計數

試試這個:

從a.t1中選擇a.t1,count(a.t1)作為cnt from(從t1中選擇t1 UNION全部從t2中選擇t2作為t1)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM