Hi I'm trying to get the num rows of every data that equal on the value produce by foreach loop here's my samp code
$query = $this->db->query("SELECT * FROM tblsamp");
foreach ($query->result() as $row){
$subquery = $this->db->query("SELECT * FROM other_table WHERE foo like '%$row->some_col%'");
echo $subquery->num_rows();
// Ill get the num rows here equal on the value of $row->som_col
}
Here's the sample output so you can visualize the data"
name | NoRows
name1 | 6
name2 | 6
name3 | 6
name4 | 6
the problem is if name1 detect '6' rows the name2,name3,name4. and so on will also output '6' rows which is that the number of rows on each name is different.
Why im getting the same result of name1?
Hoping for your answer guys! thanks!
Why don't you use group and count request ?
select t.name, count(*)
from tblsamp t
left join other_table on foo like concat('%',t.some_col,'%')
group by t.name
Related
I have 2 tables on my database. Table tableA looks like this:
taid | tanum | tarelation
---------------------------
30 | 22 | 101
31 | 88 | 101
And table tableB looks like this:
tbid | tbnum | tbrelation
---------------------------
1 | 10 | 101
2 | 20 | 101
I want to echo out all rows for tanum and tbnum - should be only 4 results echoed out, but instead my code is doubling each result echoed, so it is displaying 8 results total (should not do that). This is the unwanted result I am getting:
22
10
88
10
22
20
88
20
Why is it doing that? The result should not look like that, but like this:
22
88
10
20
Please help me fix this. This is my code:
<?php
$columns = [];
$stmt = $conn->prepare("
SELECT tableA.*, tableB.*
FROM tableA
INNER JOIN tableB
ON tableA.tarelation = tableB.tbrelation");
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_object()) {
$columns[] = $row;
}
$stmt->close();
?>
<div>
<?php foreach($columns as $column): ?>
<div><?php echo $column->tanum; ?></div>
<div><?php echo $column->tbnum; ?></div>
<?php endforeach; ?>
</div>
Use UNION concept. For that, you can use UNION or UNION ALL keyword.
Note:
While using UNION, duplicate records will be removed, so if you want to keep all records use UNION ALL.
You don't need to create sub-queries for that.
SELECT taid AS ID, tanum AS NUM, tarelation AS RELATION FROM tableA
UNION ALL
SELECT tbid AS ID, tbnum AS NUM, tbrelation AS RELATION FROM tableB;
Your SQL query does not produce a list of just the tanum and tbnum values that you show as your output. If you want a list of just the tanum and tbnum values in all tables (as you show as your desired result), this will do it:
select tanum from TableA
union
select tbnum from TableB;
I am not sure if this is what you are looking for, but it seems like you just want to append both these tables:
select a.*
from
(select taid as ID,tanum as NUM,tarelation as RELATION from tableA
UNION
select tbid as ID,tbnum as NUM,tbrelation as RELATION from tableB)a
SQL query is fine.
I believe the following result looks like something expected by you:
But you are just printing values twice by yourself:
<div><?php echo $column->tanum; ?></div>
<div><?php echo $column->tbnum; ?></div>
Row 1, "tanum": 22
Row 1, "tbnum": 10
Row 2, "tanum": 88
Row 2, "tbnum": 10
Row 3, "tanum": 22
Row 3, "tbnum": 20
Row 4, "tanum": 88
Row 5, "tbnum": 20
It's the SQL
The inner join doesn't ensure that only 1 rows in both table will be connected
I can't figure out how to get results from 2 tables, in 1 query result (can't simple JOIN)
I have these 2 tables in my MySQL database:
Table 1: sales
id
name
info
Table 2: users
sale_id
user_id
Now, every sale have different number of assigned users. Some sale have 2 users, some sale have 10 users.
In single row, I need to have columns from sale table, and all assigned users to it (connected with same Sale_id)
I need result, something like this:
enter image description here
Try this :
SELECT s.*,
(SELECT GROUP_CONCAT(u.user_id SEPARATOR ', ')
FROM users u
WHERE u.sale_id = s.id) AS users
FROM sales s
Some insight on your programming language would have been nice.
And yes, as suggested by wogsland and icoder, one typically use joins and loop through results to build en array. But the use of GROUP_CONCAT, as Yoleth pointed out, is what you need. I don’t know if it was the goal here, but it can reduce memory used in the result because there is no row repetition.
SELECT info FROM Sales AS s,
(
SELECT sale_id, GROUP_CONCAT(user_id) AS assigned_users
FROM Users
GROUP BY sale_id) AS u
WHERE s.id=u.sale_id;
In a single query, with a fancy JOIN:
SELECT s.info AS info, u.sale_id AS sale_id, GROUP_CONCAT(u.user_id) AS assigned_users
FROM Sales AS s LEFT JOIN Users AS u
ON s.id=u.sale_id
WHERE sale_id IS NOT NULL GROUP BY u.sale_id;
You can simply join two tables and get query result set like this:
saleID | saleName | userID | userName
1 | Oct Sale | 5 | Tim
1 | Oct Sale | 6 | Nik
2 | Nov Sale | 7 | Bill
Then you can walk each row and build associative array from that data:
$sales = array();
while( $row = mysqli_fetch_assoc($result)) {
if (!array_key_exists($row['saleID'], $sales)) {
$sales[$row['saleID']] = array(
'saleID' => $row['saleID'],
'saleName' => $row['saleName'],
'users' => array()
);
}
array_push($sales[$row['saleID']]['users'], array(
'userID' => $row['userID'],
'userName' => $row['userName']
));
}
Well, MySQL isn't going to return you a nice nested array like that. But you can create it by looping through the result. Assuming your MySQL connection is named $mysqli then try something like
$sales = array();
$result = $mysqli->query("SELECT sales.*, users.user_id FROM sales, users WHERE sales.id = users.sales_id");
while ($row = $result->fetch_assoc()) {
$sales[$row->id]['sales_id'] = $row->id;
$sales[$row->id]['name'] = $row->name;
$sales[$row->id]['info'] = $row->info;
$sales[$row->id]['assigned_users'][] = $row->user_id;
}
I use Codeigniter
My invalid SQL query:
SELECT *, (SELECT menu FROM sepetim WHERE SiparisId = S.Id) AS menum
FROM siparisler AS S
WHERE onay = 1 AND BayiId = '1'
ORDER BY Id desc
I have tables like this:
Table1 Table2
Id Id | Text
1 1 name1
2 1 name2
2 name3
Current result:
Wanted result:
Can you help me? Thanx.
Here is my scenario:
Database Name: Children
+-------------+---------+---------+
| child_id | name | user_id |
+-------------+---------+---------+
1 Beyonce 33
2 Cher 33
3 Madonna 33
4 Eminem 33
Database Name: Parents
+-------------+---------+---------+
| parent_id | child_id | parent_name |
+-------------+---------+---------+
1 1 Obama
2 1 Michelle
3 4 50cents
4 4 Gaga
Desired Output:
+-------------+---------+---------+
| child_id | name | parent Name |
+-------------+---------+---------+
1 Beyonce Obama (Row 1) Michelle (Row 2)
PHP SQL Query in PDO:
$sql = "SELECT Children.child_id, Children.name, Parents.parent_name
FROM Children
LEFT JOIN Parents
ON Children.child_id = Parents.child_id
WHERE Children.user_id = ?
";
$stmt = $db_PDO->prepare($sql);
if($stmt->execute(array($userId))) // $userId defined earlier
{
// Loop through the returned results
$i = 0;
foreach ($stmt as $row) {
$fetchArray[$i] = array (
'childId' => $row['child_id'],
'childName' => $row['name'],
'parentName' => $row['parent_name'],
// How do I save the multiple parents from other rows here ????
);
$i++;
}
}
How can I run a query that Joins 1 row to multiple rows in second table in PDO? I have read other topics here but I am unsure. Is it easier to add a second query that gets the linked parents for each child_id separately in a loop? I am worried that will be too much query. Can someone help me solve this?
Well, took me some fiddling to test it all out but here you go.
Unfortunately one cannot easely pivot tables in mysql but there are alternatives.
http://sqlfiddle.com/#!9/1228f/26
SELECT GROUP_CONCAT(
CONCAT_WS(':', Parents.parent_id,Parents.parent_name) ) FROM Parents where Parents.child_id=1
;
SELECT
Children.child_id,
Children.name,
GROUP_CONCAT(
CONCAT_WS(':', Parents.parent_id,Parents.parent_name) ) as parents
FROM
Children
LEFT JOIN Parents
ON Children.child_id = Parents.child_id
WHERE Children.user_id = 33
Group by Children.child_id
This query uses the group concat to concatenate all resulsts we want into a colon seperated string with the values we want, and comma's between the individual fields.
We could do some tricky magic to make them individual fields but that would break our php because we wouldnt know how much fields each query would return(adopted, orphan, no known parents, etc...)
In php you could feed them into an object
$parents = array();
$loop1 = explode(',',$row['parents']);
foreach($loop1 as $parentset) {
$parentdetail = explode(":",$parentset);// decide yourself how much detail you want in here... I jsut went with name and id.
$parent = new stdClass();
$parent->id = $parentdetail[0];
$parent->name = $parentdetail[1];
array_push($parents,$parent);
}
var_dump($parents);
Execute the below query . You will get the output as required, i just used the group by which will group the records as per the selected column
select a.child_id, name ,group_concat(parent_name) from children a, parents b where a.child_id =b.child_id group by a.child_id
HI this query works only if you are passing child id ,
select a.child_id, name ,group_concat(parent_name ) parent_name from children a, parents b where a.child_id =b.child_id and a.child_id=1
here i am using a function called group_concat which is used for concatinating the rows.It automatically takes the rows whose count is greater than 1.So no need of the extra code again
I have a database that looks like this with two tables
Items
id | Title
-----------------------------
1 Bus
2 Plane
3 Jet
4 Shoes
5 Chair
Sorting
id | CatID | ItemID | SortOrder
-------------------------------------------------------------------------------
1 3 3 3
2 3 2 1
3 3 4 2
4 3 1 0
5 4 5 4
I can't figure out how to list the Titles of the ITEMS table based on the "SortOrder" Column of the SORTING table.
Here is what I tried so far:
SELECT *
FROM Items
LEFT JOIN Sorting ON Items.id = Sorting.ItemID
WHERE Sorting.CatID = 3
ORDER BY Sorting.SortOrder
I'm not sure what I'm doing wrong
EDIT
It looks like the MySQL query is correct, the problem is happening because when I output the $row['id'] of the Items Table it is incorrect. I have an Ajax PHP update that is updating the database based on the id of an li tag.
Any ideas why the $row['id'] is outputting incorrectly? I think it has something to do with the Items.id = Sorting.ItemID
This works as expected - SQLFiddle DEMO:
SELECT i.*, s.SortOrder
FROM items i, sorting s
WHERE i.id = s.ItemID
AND s.CatID = 3
ORDER BY s.SortOrder
Try
SELECT *
FROM Items
LEFT JOIN Sorting ON Items.id = Sorting.ItemID
WHERE Sorting.CatID = 3
ORDER BY Sorting.SortOrder ASC
add DESC or ASC in ORDER BY clause.
if you use ASC then sorted result will be 0 1 2 3 4 for SortOrder.
sample php code to get title
<?php
$query = mysqli_query(above_query)or die(mysqli_error());
while($result = mysqli_fetch_assoc($query))
{
echo $result['title']. '<br/>';
}