I have 5 different tables in my dB with the structure Name|Price|Id..
I have a unique price and Id entry combination.
Using these 2, what could be the possible SQL query to fetch the name of the table in which this entry is present?
I need to fetch the name of this table in order to update the value of Price.
You really should normalise your database properly and use a single table, but if you really need a kludge then:
SELECT name, brand, id, 'Tea' as tablename
FROM TableTea
WHERE brand = 'abc'
AND id = 100
UNION
SELECT name, brand, id, 'Coffee' as tablename
FROM TableCoffee
WHERE brand = 'abc'
AND id = 100
UNION
SELECT name, brand, id, 'Chocolate' as tablename
FROM TableChocolate
WHERE brand = 'abc'
AND id = 100
And you'll have to change it if you ever add new products
if your DBMS is MySQL you can use this Query:
SELECT Result.TABLE_NAME FROM (
SELECT TABLE_NAME,COLUMN_NAME,COUNT(*) AS QTA FROM INFORMATION_SCHEMA.COLUMNS
where TABLE_SCHEMA = 'NAME_DB'
and COLUMN_NAME IN ('Name','Price','Id')
GROUP BY TABLE_NAME
) as Result
WHERE Result.QTA = 3
i have already tried to do without php
Replace NAME_DB with your Database.
You would first need to know the tables in which it's possible to have the entry. Use a loop to iterate over those tables and run the query, each time returning a result set and testing if records exist in the result set. This will tell you what tables have the entry.
General Approach:
$array = array("table1", "table2", "table3", "table4", "table5");
foreach($array as $table) {
//build your query using the table name
$query = "SELECT something FROM " . $table;
//exec your query against your db and return results
//test if records exist in result set. If true, you know the table name based on the loop iteration ($table).
}
Related
I need help to create an SQL query in order to SUM the values of specific column from all tables LIKE table_% as the tables will grow over time and this must cater for new table names based on the format below
Scheme Name: database_01
Table Names: tb_data_'YEAR'_'MONTH'
YEAR and MONTH are both values which range from all 12 months and years from 2011 to 2018.
Each Table contains a column called TOTAL_VALUE. I have a php script that triggers an SQL query to pull data from the database.
I would like to SUM the total of each tables TOTAL_VALUE column and save the value for my script below to push the array.
$sql = "SELECT TOTAL_VALUES FROM tb_data_2017_october";
$result = mysqli_query($conn, $sql);
$data = array(); while($enr = mysqli_fetch_assoc($result)){
$a = array($enr['TOTAL_VALUES']);
foreach ($a as $as){
echo "'".$as."', ";}
array_push($data, $as); }
I have been trying to alter the SQL with options such as:
SELECT id FROM table1
UNION
SELECT id FROM table2
UNION
SELECT id FROM table3
UNION
SELECT id FROM table4
However i need to cater for the ability to check all tables that are like tb_data_%
See this question for information about getting the list of tables: Get table names using SELECT statement in MySQL
You can get the list of tables in one query result, and then query each table. I'll rework your code slightly to give an example:
// Get the tables
$tables_sql = "SELECT table_name
FROM information_schema.tables
WHERE table_schema='<your DB>'
AND table_name LIKE 'tb_data%'";
$tables = mysqli_query($conn, $sql);
// Iterate over the tables
while($table = mysqli_fetch_assoc($tables)){
{
/*
* Your code
*/
// This query assumes that you can trust your table names not to to an SQL injection
$sql = "SELECT TOTAL_VALUES FROM " . $table['table_name'];
$result = mysqli_query($conn, $sql);
$data = array(); while($enr = mysqli_fetch_assoc($result)){
$a = array($enr['TOTAL_VALUES']);
foreach ($a as $as){
echo "'".$as."', ";
array_push($data, $as); }
}
You can do whatever you need once your have your list of tables. You can build one big union query (which would be more efficient than querying each table individually), or feed the tables to the MERGE engine, as in barmar's answer
Use the MERGE storage engine to create a virtual table that combines all the monthly tables.
CREATE TABLE tb_all_data (
...
) ENGINE=MERGE UNION=(tb_data_2017_october, tb_data_2017_november, ...);
List all the tables in the UNION= list, and update it whenever you create a new table.
Then you can just query from tb_all_data.
Try this- it will loop through all the tables with the pattern you want and create sums for you:
declare #table table (rowid int identity, name varchar(max))
insert #table
select name from sys.tables where name like '%yourname%'
declare #holding table (name varchar(max), sumvalue int)
declare #iterator int = 1
declare #tablename varchar(max)
while #iterator<=(select max(rowid) from #table)
begin
select #tablename=name from #table where rowid=#iterator
insert #holding
exec('select '+#tablename+' sum(TOTAL_VALUE)TOTAL_VALUE from '+#tablename+' group by +'+#tablename+'')
set #iterator=#iterator+1
end
select * from #holding
I'm using a SELECT COUNT(*) in order to verify that a user exists with PHP PDO and MySQL. I'd also like to get a specific column value. There is only ever one value/row or no value/row per user.
I'm trying to do something like this:
$stmt = $link->prepare('SELECT COUNT(*) AND column FROM table WHERE user=:user');
What I'm hoping to get back is, 1, and the column value. Where I can then bind the column value to a variable.
If not, I'll have to first do the SELECT COUNT(*) then do another query to get the column name after verifying that the user and this column exists from the SELECT COUNT(*) query.
You just need to think a little.
"count(*)" is not a special method "to verify that a user exists". It's just a query where you select count because you just have no idea what to select else.
But as long as you have a column to select, you don't need no counts anymore.
Therefore, just select your value, and as long as you are getting it, you can tell that a user exists
$stmt = $link->prepare('SELECT column FROM table WHERE user=:user');
$stmt->execute([$user]);
$col = $stmt->fetchColumn();
if ($col) {
// user exists
$something = $col; // use $col as you wanted
}
While selecting count() and a column without a group by operator is a tricky query, and you should avoid it in general.
SELECT count(*), column FROM table where user=:user
It's what you want no ?
Otherwise you can count the number of result in php
$pdo = new PDO('mysql:host=XXX.fr.mysql;dbname=YYYY', 'ZZZ', 'TTT', $pdo_options);
$response = $pdo->query('SELECT column FROM table');
$count = 0;
while ($data = $response->fetch())
{
$count++;
}
$reponse->closeCursor();
I'm trying to add a single column in a db query result. I've read about the SUM(col_name) as TOTAL, GROUP BY (col_name2).
But is there a way i can only SUM the column without any GROUPing? I a case whereby all col_name2 are all unique.
For example... I have a result with the following col headers:
course_code
course_title
course_unit
score
grade
Assuming this have 12 rows returned into an HTML table. Now i want to perform SUM() on all the values (12 rows) for the column course_unit, in other to implement a GPA school grading system.
How can i achieve this.
Thanks.
SELECT SUM(col_name) as 'total' FROM <table>
GROUP BY is required only if you want to sum subsets of the rows in the table.
You can find sum or any aggregate db functions (such as count, avg, etc) for most cases without using group clause. Your sql query may look something like this:
SELECT SUM(course_unit) as "Total" FROM <table_name>;
As comments below have already pointed out: SELECT SUM(course_unit) AS total FROM your_table;. Note that this is a separate query to the one with which you retrieve the table data.
This does it in php. I'm not sure how to do it with pure sql
$query = "SELECT * FROM table";
$result = mysql_query($query);
$sum = 0;
while($row = mysql_fetch_assoc($result))
{
$sum+= intval($row['course_unit']);
}
echo $sum;
SELECT
course_code,
course_title,
course_unit,
score, grade,
(select sum(course_unit) from TableA) total
from TableA;
I need to select category ids from my sql database.
I have a variable $product_id and for each product id there are three rows in a table that i need to select using PHP.
If I do "SELECT * FROM table_name WHERE product_id='$prodid'"; I only get the one on the top.
How can I select all three category_ids which contain the same product_id?
I suppose you are using PHP's mysql functions, is this correct? I am figuring that your query is actually returning all three rows but you aren't fetching all of them.
$sql = "SELECT * FROM table_name WHERE product_id='$prodid'";
$r = mysql_query($sql, $conn); //where $conn is your connection
$x = mysql_fetch_SOMETHING($r); //where something is array, assoc, object, etc.
The fetch function gives only one row at a time. You say you need three so it needs to be executed three times.
$x[0] = mysql_fetch_assoc($r);
$x[1] = mysql_fetch_assoc($r);
$x[2] = mysql_fetch_assoc($r);
OR this would be better
while($curRow = mysql_fetch_assoc($r)) //this returns false when its out of rows, returns false
{
$categoryIds[] = $curRow['category_id'];
}
If this doesn't do it then your query is actually returning only one row and we need to see your tables/fields and maybe sample data.
SQL seems to be correct, but Why do you store product_id in categories table? if it's one-to-many relation it would be better to store only category_id in products table.
The SQL query is correct for what you want to do. It will select all the records in table_name with the field product_id = $prodid (not only 1 or 3 but any that matches the variable)
To select a few records you should use the LIMIT keyword
You should look inside your table structure and the variable $prodid to find problems.
Need to count the number of rows for each category in a MySQL table using PDO. For example, I need to have the number of entries for category 1, category 2, etc. If possible, I would like to do this without having to write out an SQL statement for each category.
Thanks!
The SQL you need is something like:
SELECT category_name, COUNT(*) AS total FROM category_table
GROUP BY category_name
This will return a result set that has one row for each category. Each row has two columns: the category name and the total number of records with that category name. The same technique works for category id's or any other key you may want to use.
You would use it this way:
$sql = 'SELECT category_name, COUNT(*) AS total FROM category_table '.
'GROUP BY category_name';
$db = new PDO($database, $user, $password);
$results = $db->query($sql)->fetchAll(PDO::FETCH_ASSOC);
// $results is now an array with the query results
Edit: added sample PHP code.