Find table name & then get data from that table. - php

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

Related

Update value from one database to another database - fastest method

I have two tables.
first datatable structure has nine columns but the important three are:
code | name | value
2D3 | name test | 0.12
the second table has the same three columns.
Now I want to update all rows of the first table with the values of table two where code AND name are the same as in table two.
So my current idea is to do a select of all rows of table 1 with the code and name columns, than check if a row with the same code and name exists in table 2, if yes get that value and do a UPDATE query in table 1 with value of table 2.
The problem is that the two tables are hugh and I am sure that I am not using the fastest method.
anyone an idea for the fastest method to do this? Thank you very much!
EDIT: the query:
$getall = "SELECT code, name, value FROM table2";
$query = mysqli_query($conn, $getall );
while($result = mysqli_fetch_array($query))
{
$UpdateAll = "UPDATE table1 SET value = '".mysqli_real_escape_string($conn,$result["value"])."' WHERE name = '".mysqli_real_escape_string($conn,$result["name"])."' AND code = '".mysqli_real_escape_string($conn,$result["code"])."'";
$result2 = mysqli_query($conn, $UpdateAll); }
You speak of two databases but really mean two tables, don't you? In this case, you can do it with one update using a join, like this:
update table1 t1
inner join table2 t2 on t2.code = t1.code and t2.name = t1.name
set t1.value = t2.value;

Select distinct column from table

I have the database structure as shown in the below image:
I want to retrieve variant_id that belongs to particular product_id
Example :
lets say 1 and Size = L , Color = Green.
I expect mysql query to return variant_id = 7.
What is the expected query to be used in this scenario?
You can use following query.
I'm assuming your table name is table1
select variant_id from (select * from table1 where
product_id=1 and ((attribute_name='Size' and value='L')
or (attribute_name='Color' and value='Green'))) as temp
group by variant_id having count(*)>1

MYSQL Group By same id?

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.

trying to output the correct value from SQL query from comparing a different table

I'm very new with SQL and need assistance on how I can accomplish this task using the correct query.
I have 2 tables that I need to use. Table "TB1" has:
id Name
1 bob
2 blow
3 joe
table "TB2" has:
compid property
1 bob
2 blow
I am trying to get which compid is missing in "TB2" and insert it from "TB1"
the query I am doing is:
SELECT id, name from TB1, TB2 where id <> compid
what I get is 2 ouputs of Id 1, and 2, and 3 outputs from id 3. by using php:
for($i=0;$i <= mysql_num_rows($comp)-1; $i++)
{
echo mysql_result($comp, $i, 0)."<br>";
}
and I expected the ouput 3 but instead got this:
1
1
2
2
3
3
3
I understand its comparing all the rows within the table but is there a way to achieve what I am looking for?
Thanks for your time.
You are performing an implicit Cartesian JOIN which results in every row against every other row. You need to specify what attribute JOINs the two tables.
Using implicit syntax (not recommended):
SELECT id, name
FROM TB1, TB2
WHERE id <> compid
AND TB1.Name = TB2.property <-- Column join
Using explicit syntax:
SELECT id, name
FROM TB1
JOIN TB2
ON TB2.property = TB1.Name <-- Column join
WHERE id <> compid
To accomplish your goal you would need something along the lines of:
SELECT TB1.id, TB1.name
FROM TB1
LEFT JOIN TB2
ON TB2.property = TB1.Name
WHERE TB2.compid IS NULL
See it in action
It's best practice to always alias the columns you select to prevent ambiguity.
To select it you can do:
SELECT *
FROM TB1
WHERE id NOT IN (
SELECT compid
FROM TB2
);

MYSQL working slowly as query with subquery than 2 queries (+php)

I have table (about 80'000 rows), looks like
id, parentId, col1, col2, col3...
1, null, 'A', 'B', 'C'
2, 1, ...
3, 1, ...
4, null, ...
5, 4, ...
(one level parent - child only)
and I need get all dependent rows -
SELECT ...
FROM table
WHERE id = :id OR parentId = :id OR id IN (
SELECT parentId
FROM table
WHERE id = :id
)
but why this request working slowly instead 2 request - if I get parentId on php first?
$t = executeQuery('SELECT parentId FROM table WHERE id = :Id;', $id);
if ($t) {
$id = $t;
}
$t = executeQuery('SELECT * FROM table WHERE id = :id OR parentId = :id ORDER BY id;', $id);
PS: max depends rows < 70
PPS:
id select_type table type possible_keys key key_len ref rows Extra
1 PRIMARY product ALL PRIMARY,parentId NULL NULL NULL 73415 Using where
2 DEPENDENT SUBQUERY product const PRIMARY,parentId PRIMARY 4 const 1
Change the IN for an equal =
SELECT ...
FROM table
WHERE id = :id OR parentId = :id OR id = (
SELECT parentId
FROM table
WHERE id = :id
)
or change it to a join:
SELECT ...
FROM table
inner join (
SELECT parentId
FROM table
WHERE id = :id
) s on s.parentID = table.id or s.parentID = table.parentID
Well, in the first case, MySQL need to create an intermediate result, store it in memory and then iterate over it to find all the relevant id in the table. In the second way, assuming you correctly created an index on id and parent id, it simply go straigth to the index, find the relevant rows, and send you back the result immediately.
UNION works faster for this case
this allows first query to user UNION INDEX and second just uses inner join, then merges results.
SELECT *
FROM `table`
WHERE id = :id OR parentId = :id
UNION
SELECT t1.*
FROM `table` t1 JOIN `table` t2 ON t2.parentId = t1.id AND t2.id = :id
An EXPLAIN might shed some more light on the problem for you.
Look into EXISTS, or rewriting your query as a JOIN.
It's a long shot but in first case you have "IN" statement of the WHERE part of the query. Maybe MySQL tries to optimize the query as if there would be multiple options and in the second case there is no IN part, so the compiled query is more straight forward for the database - thus utilizing the indexes in better manner.
Basically for 2 queries on the same connection the overhead of performing the queries should be minimal and irelevant in this case. Also subqueries in general are not very optimizable by the query parser. Try using JOIN instead (if possible).

Categories