Insert a new field when primary keys from two separate tables match - php

I have two tables one is called Players and the other is importdata. The importdata table consists of two fields the player id (PID) and the photo (Photo).
In the Players table I created a column for the Photo field to be imported into. What I would like to do is take the Photo field from the importdata table and insert it into the photo_high field in the Players table where the PID fields match.
I thought something like this would work, but it says that there is an unknown column.
INSERT INTO (`photo_high`)
SELECT PID, Photo
FROM importdata
WHERE Players.PID = importdata.PID
Can this be achieved with an SQL statement or do I have to write some kind of script? Any guidance would be great.
Players
PID
photo_high (empty)
importdata
PID
Photo (full of content)

I think you want update rather than insert:
update Players p join
ImportData id
on p.Pid = id.pid
set photo_high = id.photo;
insert creates new rows in a table. update changes values in existing fields.

Related

How can i insert data in table with a join sql?

i have 2 tables on db.
First table:
users
id|name|mail|password|group
second table
scores
id|name|score
The idea is get the name from users using the id (this id already know because i get that by php), then insert a score in table scores using the name obtained by a id.
I suppose that can i do with a inner join between users and scores.
How can i do that?
Insert into scores(id, name, score)
select ID, name, score(that you can pass)
from users
where id = (parameter pass by PHP)
Agree. You can simply use this:
INSERT INTO scores values (null, (select name from users where users.id= 1),100);
Replace the score and id with the values you get.
Assume you have the auto increment for your ids.

mysql join two tables likes and posts

Here is my php/MySQL task:
I have a table POSTS that contains num field that is the primary key and other information fields about the post (author, title, etc.). I also have a table LIKE that contains a userId field that is the primary key and a field POST that corresponds to the num field in posts. Given a specific userID, I need to get all of the rows from the POSTS table that the userId 'likes'.
Table 1 - posts
-num
-author
-title
Table 2 - likes
-userId
-postId
This is all in php so my first idea was to get all of the rows from the LIKES table where the userId matches the one given and store those rows in an array. Then I would iterate through the array and for each row I would search get the row of the POSTS table where postId=POSTS.num. However, this seems like it would be rather slow, especially since each iteration through the array would be a separate mysql query.
I am assuming there is a faster way. Would it be to use a temporary table or is there a better way to join the tables? I have to assume that both tables contain many rows. I am a mysql novice so if there is a better solution please explain why it is better. Thank you in advance for you help!
Try the following query:
SELECT
`posts`.*
FROM
`likes`
INNER JOIN
`posts` ON
`posts`.num = `likes`.postId
WHERE
`likes`.Userid = {insert user id here}
Depending on your schema (not sure if each record in 'likes' has to be unique, you may want to use the DISTINCT keyword on your select to filter out duplicates.
SELECT poli.* FROM (
SELECT po.* FROM posts po
JOIN likes li
ON li.postId = po.num
WHERE li.userId = '$yourGivenUserId'
) AS poli
$yourGivenUserId is the given userId.

MySQL create table containing values from a column in another table

Lets say I have a table tilistings with a dozen columns, and about 2,000 rows there is one column cityname that has probably 50 different values in it. What I want to do, is search through the tilistings and create another table that just contains the 50 different values from cityname without duplicating any names....basically if cityname had the values a,b,a,c,b,b,d,a,a,d,d,c I would only want the new table to contain a,b,c. Is there a pre-built MySQL function to do so? Otherwise, just point me in the right direction to do this with PHP. I can create the table, just looking to populate it.
Or do it all in SQL, if you already have created a table named cities with a single column cityname:
INSERT INTO `cities` (`cityname`)
SELECT DISTINCT `cityname` FROM `tilistings`;
Or crate the table from the SELECT:
CREATE TABLE `cities`
SELECT DISTINCT `cityname` FROM `tilistings`;
You can get the unique city names by performing the following query:
SELECT DISTINCT cityname FROM tilistings
Then loop through those and INSERT them into your new table with PHP or INSERT INTO ... SELECT.

What are the better ways with INSERT on relational tables?

I'm experiencing my first mysql INSERT tests and I'm using these tables:
table employees
-> employee_id
-> employee_name
-> employee_surname
-> employee_url
table areas
-> area_id
-> area_city
-> area_address
-> area_country
table agencies
-> agency_id
-> agency_name
-> agency_url
table node_employees
-> node_id
-> employee_id
-> area_id
-> agency_id
I would store data in table_employee, table_areas and table_agency but I'm not forced to save all the data simultaneously, so I could create an employee, and subsequently an agency or an address.
In a case of singular data insert, should I use something like this or shoud I use directly the table node_employees, if yes, how can I do it?
INSERT INTO employees (employee_name, employee_surname, employee_url)
VALUES ('Roger', 'Waters', 'http://pinkfloyd.com')
INSERT INTO agencies (agency_name, agency_url)
VALUES ('Google', 'http://google.com')
INSERT INTO areas (area_city, area_address, area_country)
VALUES ('Rome', 'Via Roma, 123', 'Italy')
To link rows each other I've created node_employees, a relational table.
I use it to link an employee with an area or an agency, so what I should do to link data with this relational table?
SELECT employee_id FROM employees WHERE employee_name = 'Roger'
SELECT agency_id FROM agencies WHERE agency_name = 'Google'
// I'll get their ids in php
$php_employee_id
$php_agency_id
// and then
INSERT INTO node_employees (employee_id, agency_id)
VALUES ('$php_employee_id', '$php_agency_id')
I have also another doubt, what I should do if I need to link an employee with an area? shoud I use a different query, so a query for every possibility?
// so, not this
$php_employee_id = 12;
$php_agency_id = 7;
$php_area_id = null;
INSERT INTO node_employees (employee_id, agency_id, area_id)
VALUES ('$php_employee_id', '$php_agency_id', '$php_area_id') // will this remove the previous data with null in area_id?
I am assuming the agencies and areas are one to many relationships. in other words each employee can be assigned to multiple agencies and areas. If not then I would simply add the agency_id and area_id fields to the employees table and not even create the node_employees table.
With the above in mind...
From the description you have provided it appears agencies and areas are relativally static. So they should be set up before the employee data is entered.
Then when inserting the employee use mysql_insert_id() to return the id of the record you just created. (I am assuming the employee_id is an auto increment field)
Then do as you have said
SELECT agency_id FROM agencies WHERE agency_name = 'Google'
// I'll get their ids in php
$php_employee_id <== from mysql_insert_id() after inserting employee record
$php_agency_id <== from above agency Select
// and then
INSERT INTO node_employees (employee_id, agency_id)
VALUES ('$php_employee_id', '$php_agency_id')
for your last query
An INSERT statement adds a new record it will not replace the existing record. if the existing record has a unique index such as 'employee_id' it will fail with an error. You need to use UPDATE to do that OR the REPLACE statement which UPDATEs a record if one exists or INSERTs if the record doesnt exist. make sure you read up on it because it works via unique indexes.
DC
To link rows each other I've created node_employees, a relational table. I use it to link an employee with an area or an agency, so what I should do to link data with this relational table?
That should be two tables - one for relating employees to agencies, and a separate one for relating employees to areas. You haven't mentioned anything relating agencies to areas, giving the impression they are independent of one another...
Regardless, the node_employees.employee_id should be a foreign key to EMPLOYEES.employee_id, in order to ensure that the employee must already exist as a valid value in the system. Likewise for the agency_id between node_employees and agencies tables.
Because of those relationships, values have to exist in the EMPLOYEES and AGENCIES tables before they exist in the NODE_EMPLOYEES table. That makes the NODE_EMPLOYEES table in a "child" relationship with the other two tables, so your three INSERT statements would have to insert into the parents before the child, and use the values from the parents in the child.

Why is my Update command updating all of the fields that have the same ID?

Using the update command, I want to change the type_name for a specific entry in the database, but it is changing the type_name for all the entries with the same type_id.
I need it to only change that individual entry's type_name, and not the type_name that is associated with all the entries with the same type_id.
I have an update query:
$sql = 'UPDATE photos
LEFT JOIN types
ON photos.type_id = types.type_id
SET photos.photo_title = $_POST['photo_title'],
types.type_name = $_POST['type_name']
WHERE photos.photo_id = 3';
Here's the form I'm using:
<form name="form1" method="post" action="">
<input name="photo_title" type="text" value=""/>
<textarea name="type_name"></textarea>
<input type="submit" name="update" value="Update entry" />
</form>
Here's my database structure:
TABLE photos
photo_id PRIMARY KEY
photo_title
type_id FOREIGN KEY
TABLE types
type_id PRIMARY KEY
type_name
What is happening is that your join is producing the wrong set of data. You're joining the photos and types on type_id.
Now what you seem to be describing is that the types column may contain multiple rows with the same type___id. What does this mean? It means that your join will produce multiple pairs of (photos,types) for each photo (specifically, for each photo, the join will produce n rows, where n is the number of rows in types having the same type_id as the photo).
As for how to fix this, you should take a look at your database design. You seem to expect a unique row in types for each photo. How is this relationship expressed? That will enable you to get a proper ON clause for your join.
UPDATE
After looking at the table structure, it seems your database is expressing things slightly differently. As it stands you can have multiple photos with the same type (i.e. their typeid in the photos table is the same). Thus it is a bit meaningless to speak of changing the typename of just one such photo. You're merely updating the typename for a particular type, that happens to be the type of the photo whose name you were also updating.
Now what exactly are you trying to achieve, here?
If you are trying to re categorize a particular photo, then you instead want to either create a new entry in the types table and point your photo to that new record, or find an existing photo with a matching name and point the photo at that record. (I presume you already have such code in your photo insertion logic. This should be similar)
If you are trying to update the type description for a photo and all other photos with that type, then what you have will work just fine.
I'm surprised that MySQL allows this, but it looks like you're updating the name in the type table. You're probably looking to update the type_id of a single row in the photos table.
You could do that like this:
UPDATE photos
SET photos.photo_title = $_POST['photo_title'],
photos.type_id = (
select type_id
from types
where type_name = $_POST['type_name']
)
WHERE photos.photo_id = 3
Or alternatively:
UPDATE photos
LEFT JOIN types ON types.type_id = $_POST['type_name']
SET photos.photo_title = $_POST['photo_title'],
photos.type_id = types.type_id
WHERE photos.photo_id = 3
Before you run this query, you could make sure the type_name exists:
REPLACE INTO types (type_name) VALUES ($_POST['type_name'])
I need it to only change that
individual entry's type_name, and not
the type_name that is associated with
all the entries with the same type_id.
This is your fundamental problem. There's only ever going to be one record in the types database per typeid, so when you alter it, it effectively alters it for every photo that references that typeid.
If you need to store a different type_name for every photo, just create a column in the photos table and store it there.
The other way to do this is to create a new record in the types table each time a type_name is edited - possibly doing some checking to see whether any other photos are also using that typeid (if not you can safely update the existing record). But you have to implement code that does this for yourself.
If more than one row is being updated then you are not using a unique key to update the tables. It is difficult to understand the relationship of the tables but it seems to be a 1:M relationship one type can be appended to many photos?
If so then updating the photos table using the type_id in the WHERE clause will obviously update more than one table. Use only primary keys thats are unique to update if you want to update a specific row.
You must specify the relationships of the tables if you want a decent solution :)
$sql = 'UPDATE photos
LEFT JOIN types
ON photos.type_id = types.type_id
SET photos.photo_title = $_POST['photo_title'], types.type_name = $_POST['type_name']
WHERE photos.photo_id = 3 LIMIT 1';
On a side note, you shoule be doing
$photo_title = escape_function( $_POST['photo_title'] )
$type_name = escape_function( $_POST['type_name'] )
and wrapping the varialble names in ' ' in your query string.

Categories