MySQL: Insert data in different table but have same id - mysql

I have some question : "insert data in different table but have same id (auto_increment)"
This is my twice table
student
---------------------- id | name | class|
----------------------
score
--------------------------------------------- id | math | english | physical | year |
---------------------------------------------
I have some data like:
John , A , 90 ,80 ,70 ,2015
John , A , 70 ,90 ,50 ,2016
I want result Like:
student
---------------------- id | name | class|
---------------------- 1 | John | A |
----------------------
score
--------------------------------------------- id | math | english | physical | year |
---------------------------------------------
1 | 90 | 80 | 70 |2015 1 | 70 | 90 | 50 |2016
Because table of student's "id" use Auto_increment
If I want twice table have same id when I insert data
What SQL can I use ??
(I think mysql_insert_id() is Solution but not sure...)
Thank help !!

I hope you are looking for the query to do so.First of all use PDO or mysqli for interacting with the database.Here I use PDO.
function my_select($query)
{
global $dbserver,$dbuser,$dbpwd,$dbname;
$dbh= new PDO('mysql:host='.$dbserver.';dbname='.$dbname.'',$dbuser,$dbpwd);
$rs=$dbh->prepare($query); //prepared statements have numerous advantages over executing sql statements directly
$rs->execute();
return $db->lastInsertId(); //returns last inserted id of current db connection
}
And the query can be,
$l_id=my_select(query1) // query to insert into student
$query2="INSERT INTO score (id,...) VALUES ('".$l_id."',...)" ;
my_select(query2);

If you are using Auto Increament id in both tables than you need to add a column in score table for reference of studentid. For example:
Insert into student (name) values ('test');
Than use:
mysql_insert_id();
In last insert data into score table:
Insert into score (yourcolumns, studentid) values (yourcolumnvalue, last_inserted_id);
Side note: instead of mysql_*
functions use mysqli_* or PDO becuase mysql_* is deprecated and not available in PHP 7.

Related

How do I reference an attribute inside a table to a value inside a new row within the same table

I am trying to create a table which holds the historical running times (in minutes) for a host of athletes. The table holds a foreign key to the persons name, along with storing their new running time and previous running time, along with the date the run was performed.
I am trying to keep all records of runners in the same table. I want to refer to the old running time in the new entry of when a new running time is complete. I am struggling on how this relationship will work.
Below is a table explaining what I am trying to achieve.
|Name_ID {FK}|Completion_Date|New_Time|Old_Time|
| 001 | 16/02/2019 | 123 | 108 |
| 001 | 16/03/2019 | 136 | 123 |
As you the table shows, the new average from the 16/02/2019 appears as the old average in 16/03/2019.
My question is how would I construct this relationship? Is it possible to make this a relationship?
OR
Is there a more efficient way? I.e Have the following table:
|Name_ID {FK}|Completion_Date|New_Time|
| 001 | 16/02/2019 | 123 |
| 001 | 16/03/2019 | 136 |
and create a query that could use the Name_ID and completion_Date attributes to produce an output that made:
|Name_ID {FK}|Completion_Date|New_Time|Old_Time|
| 001 | 16/02/2019 | 123 | 108 |
Any help will be appreciated.
If you don't have a Mysql 8.x Server you can use this.
CREATE TABLE table1
(`Name_ID {FK}` int, `Completion_Date` varchar(10), `New_Time` int)
;
INSERT INTO table1
(`Name_ID {FK}`, `Completion_Date`, `New_Time`)
VALUES
(001, '16/01/2019', 108),
(001, '16/02/2019', 123),
(001, '16/03/2019', 136)
;
And you can use this
select `Name_ID {FK}`,`Completion_Date`,#quot old_time, #quot:=`New_Time` new_time
from table1 p,(SELECT #quot := 0) r
order by `Name_ID {FK}`,`Completion_Date`;
to get This result:
Name_ID {FK} Completion_Date old_time new_time
1 16/01/2019 0 108
1 16/02/2019 108 123
1 16/03/2019 123 136
It is based on this
Simulate lag function in MySQL
You can use lead/lag analytical functions to get the desired result -
Using your Name| completion_date| new_time runner_data table,
create a new table with below sql:
insert into new_table select name, completion_date, new_time, lag(completion_date) over ( partition by name order by completion_date desc) as old_time from runner_data;

Consolidating information in two rows in MySQL query result

I have table which looks like this (example)
+----+----------+----------+---------------+
| id | objectId | filterId | filterValueId |
+----+----------+----------+---------------+
| 1 | 55 | 111 | 2345 |
| 2 | 55 | 113 | 2567 |
| 3 | 55 | 113 | 2568 |
| 4 | 58 | 111 | 2347 |
| 5 | 58 | 115 | 2499 |
+----+----------+----------+---------------+
Now, I have query with some LEFT JOINs (main object table, this filter table, meta table and few others). I am creating frontend filtering and I got to the point where it sort of works, but I am stuck at one problem.
When I have two filters in the queue (lets say filterId=>filterValueId 111=>2345 and 113=>2567).
With query
SELECT ojectId IN tableName
WHERE (filterId = 111 AND filterValueId = 2345)
AND (filterId = 113 AND filterValeId = 2567)
I am not able to get out the information, that objectId 55 is matching both these criteria. at least not in single query. It makes sense, I know, but is there a way making MySQL to give such result? (And does this request/procedure have some technical name I could use for googling?)
Or is it best practice to split such filtering into many queries and then intersect results and get out just these which are in every result?
Sorry for using technical terms in wrong way, hopefully sou can understand what I am trying to say :)
Thanks a lot.
Consider the following...
DROP TABLE IF EXISTS my_table;
CREATE TABLE my_table
(id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
,objectId INT NOT NULL
,filterId INT NOT NULL
,filterValueId INT NOT NULL
);
INSERT INTO my_table VALUES
(1,55,111,2345),
(2,55,113,2567),
(3,55,113,2568),
(4,58,111,2347),
(5,58,115,2499);
SELECT objectid
FROM my_table
WHERE (filterid,filtervalueid) IN ((111,2345),(113,2567))
GROUP
BY objectid
HAVING COUNT(id = 2);
+----------+
| objectid |
+----------+
| 55 |
+----------+
No special name to search in google. You just wrote your fetching sql to only fetch one record instead of two, by using AND. You should use OR.
And correct IN to FROM.
SELECT ojectId
FROM tableName
WHERE
(filterId = 111 AND filterValueId = 2345)
OR (filterId = 113 AND filterValeId = 2567)
Or is it best practice to split such filtering into many queries and
then intersect results and get out just these which are in every
result?
NO! Let database to work hard and good only once. Give it all filters at once. No need to split queries.

MySQL: Get ID if exists, else insert and return ID

I am trying to construct a single query which will return the ID of the specified NAME record, or if it does not exist then insert the name and return the ID. (ID is an autoincrement field, NAME will not have duplicates but is a varchar 1024 so it cannot have the unique attribute)
My SQL query should be something like:
IF EXISTS(SELECT 1 FROM NAMES WHERE NAME='DAVE')
THEN
SELECT FROM NAMES WHERE NAME='DAVE'
ELSE
INSERT INTO NAMES(`NAME`) VALUES ('DAVE')
ENDIF;
(obviously this is not valid SQL...but I'm not sure where to begin)
Example NAMES table:
+----+----------+
| ID | NAME |
+----+----------+
| 1 | ANDY |
| 2 | BOB |
| 3 | CARL |
+----+----------+
Should I just split this into multiple queries?
Split the task you are trying to achieve :
First check if there exists a row with the specific name
If yes, select the entire row and retrieve the id ,if no insert the data into db.
You can use SELECT LAST_INSERT_ID() after your insert operation to get the id of the newly inserted row.

Combine count rows in MySQL

I've got a table in MySQL that looks roughly like:
value | count
-------------
Fred | 7
FRED | 1
Roger | 3
roger | 1
That is, it was created with string ops outside of MySQL, so the values are case- and trailing-whitespace-sensitive.
I want it to look like:
value | count
-------------
Fred | 8
Roger | 4
That is, managed by MySQL, with value a primary key. It's not important which one (of "Fred" or "FRED") is kept.
I know how to do this in code. I also know how to generate a list of problem values (with a self-join). But I'd like to come up with a SQL update/delete to migrate my table, and I can't think of anything.
If I knew that no pair of records had variants of one value, with the same count (like ("Fred",4) and ("FRED",4)), then I think I can do it with a self-join to copy the counts, and then an update to remove the zeros. But I have no such guarantee.
Is there something simple I'm missing, or is this one of those cases where you just write a short function outside of the database?
Thanks!
As an example of how to obtain the results you are looking for with a SQL query alone:
SELECT UPPER(value) AS name, SUM(count) AS qty FROM table GROUP BY name;
If you make a new table to hold the correct values, you INSERT the above query to populate the new table as so:
INSERT INTO newtable (SELECT UPPER(value) AS name, SUM(count) AS qty FROM table GROUP BY name);
Strangely, MySQL seems to do this for you. I just tested this in MySQL 5.1.47:
create table c (value varchar(10), count int);
insert into c values ('Fred',7), ('FRED',1), ('Roger',3), ('roger',1);
select * from c;
+-------+-------+
| value | count |
+-------+-------+
| Fred | 7 |
| FRED | 1 |
| Roger | 3 |
| roger | 1 |
+-------+-------+
select value, sum(count) from c group by value;
+-------+------------+
| value | sum(count) |
+-------+------------+
| Fred | 8 |
| Roger | 4 |
+-------+------------+
I was surprised to see MySQL transform the strings like that, and I'm not sure I can explain why it did that. I was expecting to have to get four distinct rows, and to have to use some string functions to map the values to a canonical form.

MYSQL INSERT SELECT problem

i have a little difficulty in understanding how to do some INSERT SELECT.
For instance i have two tables.
TABLE : users
id | name | gender
1 | John | m
2 | Mary | f
TABLE : website
fid | url | id
1 | www.desilva.biz | 2
2 | gidhelp.com | 4
Now let's say i want to add another query to the table website. I get two variables, lets say:
$user = John;
$site = "www.google.com";
i want to select the id of John from users table and insert it into website table in one statement.
How can i do it?
Assuming your variables are already escaped properly and are not subject to SQL injection:
INSERT
INTO website (url, fid)
SELECT $site, id
FROM users
WHERE name = $user