简体   繁体   中英

How to count fields on WHERE Clause

I want to ask something about Counting on WHERE clause. I have researched about it, but not found any solution.

I have 2 tables:

Table1 contains:

id, level, instansi

Table2 contains:

id, level, table1ID

Question:

How to display table1.instansi only if the number of rows of table2 less than 2 .

Condition

table2.table1ID = table1.id
select t1.* 
from table1 t1 join table2 t2 on t2.table1ID=t1.id
group by t1.id
having count(*)<2

One method can be to make a query to select all rows and then count rows

$query = ("SELECT * from table ");

$result = mysqli_query($con, $query);

$count = mysqli_num_rows($result);

use $count in if condition

you need to use having clause to use count in where clause

select t1.instanci
from table1 t1 inner join table2 t2
   on t1.table1id=t2.table2id
group by t2.table2id
having count(t2.table2id)<2

You need to use Having clause to add the condition to aggregate function such as "count"

http://www.w3schools.com/sql/sql_having.asp

Select t1.instanci From table1 t1 inner join table2 t2 on t1.table1id=t2.table2id
Group by t2.table2id Having count(t2.table2id)<2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM