My in-experience in using join statements has come-a-cropper for me, and Im not even sure if that is what is required here.
Here is the situation:
I have two tables.
Table two has a column with a foreign key to table one.
I want to select certain column data from table one, but at the same time count(*) how many rows in table two are linked to table one.
I know this can be done easy using two statments seperatly, but I imagine there is a solution using just one query.
Here are the two table examples:
create table table_one (
id int unsigned not null AUTO_INCREMENT,
name char(60) not null DEFAULT '',
status tinyint(1) unsigned not null DEFAULT 0,
PRIMARY KEY (id)
);
create table table_two (
id int unsigned not null AUTO_INCREMENT,
table_one_id int unsigned not null,
PRIMARY KEY (id),
FOREIGN KEY table_one_id REFERENCES table_one(id) ON DELETE CASCADE
);
Here are the two queries I wish to combine:
$sql1 = "SELECT id, name FROM table_one";
$stmt = $conn->query($sql1);
// Cycle through result
while($fetch = $stmt->fetchObject())
{
$table_one_id = $fetch->id;
$name = $fetch->name;
$sql2 = "SELECT COUNT(*) FROM table_two, table_one WHERE table_two.table_one_id = table_one.id";
}
This would give a result like:
Table One Id
Table One Name
Table Two Row Counts Linked
1
'this is first record in table one'
6
2
'this is second record in table one'
9
3
'this is third record in table one'
1
4
'this is fourth record in table one'
0