I have the following 2 tables :
TABLE 1: user
id s_id first_name last_name
----------------------------------
1 2 test test
2 2 hello test
3 2 now hello
4 1 john smith
TABLE 2: section
id section_name
-------------------
1 first
2 my section
3 other section
based on the above two tables , I would like to write a MYSQL query to :
SELECT ALL from user table and GROUP THEM BY s_id ( SAME s_id) , how could I do that?
I would like to get all the s_id = 2 ALL grouped together as an array or object but controlled by s_id? so I would loop through the s_ids and print out the first and last name?
Here is an Example of the output:
$sections = array['my section'](array('first_name'=>'test' , 'last_name'=>'test'),
array('first_name'=>'hello' , 'last_name'=>'test'),
array('first_name'=>' now' , 'last_name'=>'hello'))
thanks
Simply
SELECT * FROM `user` GROUP BY `s_id`
But you have different question in your title and in your content.
So what you want in PHP is something like this:
while($row = your sql fetch)
{
$array[$row['s_id']][] = array('first_name' => $row['first_name'], 'last_name' => $row['last_name']);
}
print_r($array);
If you need all the users with s_id = 2 than:
SELECT * FROM `user` where `s_id` = 2 # this will give 3 users
otherwise if you group with s_id you'll get only one user for each section, and I think you don't want that
To show all, than you have to run query :
SELECT user.*, section.section_name FROM `user`
INNER JOIN section ON section.id = user.s_id
And trick it in PHP:
$query = "
SELECT
user.*,
section.section_name
FROM `user`
INNER JOIN section
ON section.id = user.s_id
";
$result = mysqli_query($conn, $query);
$final_data = array();
while($data = mysqli_fetch_assoc($result))
{
$final_data[$data['section_name']][] = $data;
}
print($final_data); // to see the result
Take a look at mysqli_fetch_array function in php.
You need to cycle the query result with this php function and put them in an array, you do not need to group anything in sql, but only:
select * from user order by s_id
In the php cycle you can populate your array as you need.
Related
I have two tables,
#table 1 contains the following data structure
NO category_name category_code amount type
1 provident_fund PF 1000 Deduction
2 Home Allowance HM 12000 Earning
3 Basic_pay BP 35000 Earning
#table 2 contains the following data structure
NO group_name payroll_cat_name
1 permanent PF,HM,BP,TX
1 visiting HM,BP
from the table 2, I can get the value of payroll_cat_name using the query
$a = "Select payroll_cat_name from table_2";
using the above query, I'm getting the value PF,HM,BP,TX.
Now, I have to use this multiple values PF,HM,BP,TX in order to get the sum amount from table 1.
Following is my code that I have tried,
include "../db.php";
$a = "Select payroll_cat_name from table_2";
$b = mysqli_query($con,$a);
$c = mysqli_fetch_array($b);
$d = $c["payroll_cat_name"];
echo "$d";
$myArray = explode(',', $d);
print_r($myArray);
$tr = "select SUM(amount) as am from table_1 where category_code in ($d)";
$rt = mysqli_query($con,$tr);
$new = mysqli_fetch_array($rt);
$gh = $new["am"];
That’s a poor data model. There should be a separate table to store the relation between groups and categories, which each tuple on a different row. The linked commented by sticky bit on the question gives great explanation on how and why.
For your current structure, one option using uses find_in_set() and a subquery:
select t2.*,
(
select sum(t1.amount)
from table_1 t1
where find_in_set(t1.category_code, t2.payroll_cat_name)
) as t1_amount
from table_t2 t2
Hi i want to acheive the following results for the purpose of a search script in php
i have 2 tables like this
Table 1 :
-----------------------------
id l name l url l image url l
-------------------------------
Table 2 :
-----------------------------------
id l tableoneid l desc l content l
------------------------------------
Note : (Table 1 --> id) = (Table 2 ---> tableoneid)
what i want to acheive is to get a MYSQL query that search :
Step 1 : The table 2 column [content] when i get the result i need
their [tableoneid] values,
Step 2 : Next i want to use that in order to search the Table 1 column 1
Step 3 : The final results would be the corresponding [image url] column of the Step 2 results
how can i acheive that with php/mysql
thank you very much !
Something like this:
SELECT * FROM <Table 1>
WHERE id IN (
SELECT DISTINCT(tableoneid) FROM <Table 2>
)
Change <Table 1> and <Table 2> with your actual table names.
This is one of the primary uses of JOINs.
SELECT t1.`image url`
FROM `Table 2` AS t2
INNER JOIN `Table 1` AS t1 ON t2.tableoneid = t1.id
WHERE [some condition involving t1.content]
;
I would strongly suggest not having any sort of non-alpha characters (other than _ in your table and field names.)
$query = "select
t1.`image url`
from
`Table 1` as t1
join
`Table 2` as t2 on t1.id = t2.tableoneid
where
t2.content = :table2ContentSearch";
$statement = $dbh->prepare($query);
$searchItem = "what you are searching for";
$statement->bindParam(':table2ContentSearch', $searchItem);
if($statement->execute()){
while($row = $statement->fetch()){
print_r($row);
}
}
you should also read up on sql joins. https://en.wikipedia.org/wiki/Join_%28SQL%29.
So I have a table where some of the products repeat with but have a different value on number of clicks.
name ---- clicks
iPhone 4
Samsung 2
iPhone 1
Samsung 5
my select function is :
$select_table2 = 'SELECT * FROM `mytable`'; //WHERE NAME IS THE SAME
$sql2 = $db->query($select_table2);
while ($row = mysqli_fetch_array($sql2)) {
echo $row["name"];
echo $row["clicks"];
}
I need this output:
iPhone 5
Samsung 7
I don't want to merge the same rows because they have one more column that is different. So please do not suggest simply to merge them and update the clicks...
UPDATE:
$pull_request = 'SELECT SUM(e.product_clicks),e.product_id, u.name, u.product_id FROM `oc_aa_affiliatecollclicktracking` AS e GROUP BY e.product_id LEFT JOIN `'.DB_PREFIX.'product_description` AS u ON e.product_id = u.product_id';
I tried it like this but it's not working
use sum() and also GROUP BY name to get desired output.
$select_table2 = 'SELECT name,SUM(clicks) FROM `mytable` GROUP BY name';
$sql2 = $db->query($select_table2);
while ($row = mysqli_fetch_array($sql2)) {
echo $row["name"];
echo $row["clicks"];
}
while will produce,
iPhone 5
Samsung 7
For more info
SUM()
GROUP BY
EDIT
Group by should come after join.
$pull_request = 'SELECT SUM(e.product_clicks) as clicks,e.product_id, u.name, u.product_id FROM `oc_aa_affiliatecollclicktracking` AS e
LEFT JOIN `'.DB_PREFIX.'product_description` AS u ON e.product_id = u.product_id
GROUP BY e.product_id';
You want to perform a SUM command by group
$query = "SELECT `name`,SUM(`clicks`) FROM `mytable` GROUP BY `name`";
Edit: The other answer was more complete than mine. I forgot to select name field. Added.
What you need is an aggregate function for suming the clicks [SUM(clicks)], and a Group By clause for defining the classification criteria [GROUP BY name].
The other answers where wrong in the sense that are assuming that by changing the select field list adding the aggregate 'SUM', the associative references (eg: index strings of the $row array ) remains the same, the correct query would be:
$select_table2 = 'SELECT name, SUM (clicks) AS clicks FROM mytable GROUP BY name';
Note the alias on SUM(clicks) AS clicks, so the fields returned in the array $row keep their indexes (clicks, names... instead of 'SUM(clicks)')
And the rest is basically the same.
Cheers!
Try :
$select_table2 = 'SELECT name, SUM (clicks) FROM mytable GROUP BY name';
Model
ID Model
1 1
2 2
3 4
4 10
Model-table
ID model_id table_name
1 1 table1
2 3 table2
3 4 table3
Note: It is not important that every model requires table_name.
I find the table_name of model width id 3, it is table2. It is so simple fo find it, I do not see the reason to write here my sql. After finding table2, I should select from table2 and find all parametres. In this case I should write second sql. Here is the structure of table2
Note: We can find all parametres of model_id with 3.
table2
ID model_id param1 param2 param3
1 3 0 5 10
My question:
I am looking for the way, firstly find suitable model_id in model_table and fetch table_name, THEN SELECT from table_name and fetch all parametres with 1 SQL.
Note: I have id and model_id variables on my PHP PAGE. So, we need to use Limit 1 and fetch suitable data to 1 id and model_id.
You have to do this in two queries as table names cannot be dynamic. Your code should look something like this:
$mysqli = new MySQLi(/*connection details*/);
// Fetch table name
$query = "SELECT table_name
FROM model-table
WHERE model_id = 3";
$result = $mysqli->query($query);
$row = $result->fetch_assoc($result);
$table = $row['table_name'];
// Fetch data from table2
$query = "SELECT ID, model_id, param1, param2, param3
FROM $table";
$result = $mysqli->query($query);
while($row = $mysqli->fetch_assoc($result)) {
// do something with the data from the table...
}
Not really what you are looking for, but this can help you too
Find all the tables of a database
SHOW TABLES
Find all the columns of a table
DESCRIBE table_name
I would like to create an array (in php) from sql results like this:
We have the sql-table "Posts" which stores the Name and the Message.Example:
Name | Message
John | Hello
Nick | nice day
George | Good bye
John | where
What i want is to output the names of people who have posted a message but dont display the same names more than 1 time.
So the output would be John,Nick,George.
(From these records, we see that John has posted 2 messages, but at the final output, we see only one time his name).
Is this somehow possible?
Thanks in advance.
Try:
$sql = <<<END
SELECT DISTINCT Name FROM Posts
END;
$query = mysql_query($sql) or die($sql . ' - ' . mysql_error());
$names = array();
while ($row = mysql_fetch_array($query)) {
$names[] = $row[0];
}
print_r($names);
SELECT DISTINCT
You could run a SQL query to just select the distinct names, and nothing else:
SELECT DISTINCT Name FROM Posts;
This will give you a result set consisting of distinct Names values, with each unique value only being returned 1 time in the set.
to get the count you will need to aggregate using group by:
SELECT
NAME
, COUNT(*) as Posts
FROM
Posts
GROUP BY
NAME
Here is the SQL if you are not averse to group BY
select count(name) as N, name from posts group by name ;
People having more than 1 post
select count(name) as N, name from posts group by name having N > 1 ;