php Mysql avoid insert into duplicate entries - php

I have two tables names 'users' and 'bursary'.
I want to copy all the username into 'bursary' table from 'users' table with condition the user Department=Bursary
I want to avoid duplicate entries.
my code is ,
$query25 = "INSERT INTO bursary (UserName)
SELECT users.UserName
FROM users
WHERE users.DepartCent='Bursar'";
$result25=mysql_query($query25);
I have tried but not working, can anyone help me on this? Please help me.
My user Tables look like this,
UserID UserName DepartCent
1 a bursary
2 b registar
3 c bursary
4 d bursary
I want to select all the UserName and InsertINTO table bursary where the DepartCent='bursary'

On your select have you tried the 'unique' keyword? Or is the issue adding names to the users table that are already on the user table.
Both are do-able, is this a one shot thing, or needs to be done often?

you can use group by condition to eliminate duplicate entry from table1 to table2
INSERT INTO bursary (UserName) SELECT users.UserName FROM users WHERE users.DepartCent='Bursar' group by users.UserName
OR
You can use this one.
INSERT INTO bursary (UserName) SELECT distinct(users.UserName) FROM users WHERE users.DepartCent='Bursar'

Related

PHP How to INSERT to Table Many Times in Once

I have a logical problem with my database, let me explain. There is my system:
I have users and admins.
Admins can create project and if they needed they can add the related users on the project.
1 user can work many projects and 1 project can have many users.(many to many)
I build relational database and it works fine. But the problem is, which users are working on which project(s) ? I don't know how to INSERT them to database. Admins can choose the users from the list and then the selected users should stored with the dependent project. But I couldn't managed to INSERT it to database. Here my tables and some codes.
--projects-- --users-- --projectUsers--
userId userId userId
creationDate registerDate projectId
projectId email
title permission
priority name
content surname
endDate birthDate
password
$sql="INSERT INTO projects (
projectId,
userId,
creationDate,
title,
priority,
content,
endDate
)VALUES(
'$projectId',
'$userId',
'$creationDate',
'$title',
'$priority',
'$content',
'$endDate'
)";
$result=mysql_query($sql) or die (mysql_error());
$sql2="INSERT INTO projectUsers (
projectId,
userId
)VALUES(
'$projectId',
'$userId'
)";
$result2=mysql_query($sql2) or die (mysql_error());
The table "projectUsers" stores 2 foreign keys. When the admin creates a project, his userId and the new projectId stores on the "projectUsers" and also stores on the "projects" table. But admin will choose the which users will depended with this project, and he can choose more then one in once. How should I INSERT the dependent users on the data base. And also I don't want to store more then 1 user in a row. And I should able to get answer this queries:
which users are working on which project(s) ?
which users are working on this project ?
This user working on which(s) project ?
Example: Admin creates a new project and select 3 dependent users. I want to insert them the table "projectUsers".When admin creates the project, I want to see my "projectUser" table like this:
userId projectId
1 1
2 1
3 1
P.S: The "userId" on the "projects" table shows me the who created this project. Like an owner.
Remove the userId from your projects table, you're storing that information in the ProjectUsers association table anyway. For every user working on a project, you have to create a separate row in the ProjectUsers table.
From there on, all your retrieval queries are just basic three table joins:
1. Which users are working on which project(s)?
SELECT * FROM Projects p
LEFT JOIN ProjectUsers pu
ON p.projectId = pu.projectId
LEFT JOIN Users u
ON pu.userId = u.userId
2. Which users are working on this project?
SELECT * FROM Projects p
LEFT JOIN ProjectUsers pu
ON p.projectId = 123 AND p.projectId = pu.projectId
LEFT JOIN Users u
ON pu.userId = u.userId
3. This user is working on which projects?
SELECT * FROM Users u
LEFT JOIN ProjectUsers pu
ON u.userId = 123 AND u.userId = pu.userId
LEFT JOIN Projects p
ON pu.projectId = p.projectId
The Projects and Users need to be created first for the foreign key, then simply 1, 2 & 3. Add each user for each project that is selected.
INSERT INTO ProjectUsers (userId, projectId) VALUES (1, 1);
INSERT INTO ProjectUsers (userId, projectId) VALUES (2, 1);
INSERT INTO ProjectUsers (userId, projectId) VALUES (3, 1);
Other than this we are really struggling to understand the context of your problem. You've tagged the problem as SQL, but you have the query to do the INSERT correct. What we don't have is a full definition of the table - if that is raising errors.
If you're problem is is within the PHP, then you've got too many SQL tags, because that is what people are trying to solve.
Please, Please, Please change the UserId in Projects to be OwnerUserId - the description about what this data field represents is as important as indicating what table it joins to, so concatenating these together gives full meaning to the field, and removes ambiguity.

Insert (join of two tables) into a different table

I have two tables with a bunch of stuff I don't need in them. One has info about a user and the other their password.
I have a new table that will store both their info and password together.
Additionally, the user info table has separate fields for first name and last name and I need to combine them to place them in the "name" column and add a space between them.
I need to do this without disrupting (modifying) either of the old tables.
I also need to be able to add an integer value to the id column.
I would think the basic syntax looks like this, but don't know what to do past here
INSERT INTO newtable (id, name, email, password) VALUES ((JOIN statement?), (JOIN statement?), (JOIN statement?), (JOIN statement?))
How can I accomplish this with a script?
Old table 1 (oldtable1):
User ID (id)
Password value (pass)
Old table 2 (oldtable2):
User ID (id)
First name (fname)
Last name (lname)
Email (email)
New table (newtable):
id
name
email
password
SELECT id, name, email, password INTO NewTable
FROM
(
SELECT o1.id, CONCAT(o2.fname, ' ', o2.lname), o2.email, o1.Password
FROM oldTable1 AS o1
JOIN oldTable2 AS o2
ON o1.id = o2.id
)
SELECT ID, Password, Name, Email INTO NewTable
FROM (SELECT ID, Password
FROM oldTable1
FULL OUTER JOIN oldTable2
ON oldTable1.ID=oldTable2.ID)
Try that... I'm no genius but it should work :)
IN SQL-Server you can do it this way if NewTable not exists yet.
SELECT IDENTITY(INT,1,1) id, name,email,password
INTO newtable
FROM oldtable1 ot1
join oldtable2 ot2 on ot1.UserID=ot2.UserID
and if it already exists
insert into newtable (name,email,password)
select name,email,password
FROM oldtable1 ot1
join oldtable2 ot2 on ot1.UserID=ot2.UserID
Are you sure you need a new table for join of two tables? Ever heard of views? You can use that.
CREATE VIEW myView AS
SELECT oldtable1.id, oldtable1.pass, oldtable2.fname, oldtable2.email
FROM oldtable1 JOIN oldtable2 ON oldtable1.id = oldtable2.id

SQL structure with JOIN

I'm having some trouble figuring out how I should build my database for this project i'm currently working on. Fishing-related.
I'm just not sure how to set up my tables.
Table 1(ID, username, email etc)
Table 2(fish, weight, length etc)
How do i join these two tables? Should I have a column named ID in the 2nd table aswell? Because I need to know which user uploaded what fish. I'm just not sure how to do that.
Any help is appreciated.
Yes you have to, and that is called Relation Databases this is example
Users (UserID, UserName, Password)
Fish (FishID, UserID, FishName, Length, Weight)
and then you connect them using UserID
select u.UserName, f.FishName, f.Length, f.Weight
from Users u
LEFT JOIN Fish f on (f.UserID=u.UserID)
and if you are looking for specific user then just add at the end
WHERE u.UserID=#UserID
Looking at you're table structure I think it's best to change the id name in table 1 to *user_id* and add a column in the second table also named *user_id*. Joining using the columns is then very simple using the following query:
SELECT *
FROM table1
JOIN table2 USING (user_id)
Other possibility would be to add a column named *user_id* (or something else) to table2 and create a query like:
SELECT *
FROM table1
JOIN table2 ON table2.user_id = table1.id
In this case, you set the columns to use for the join in the 'ON .. = ..' structure.

Mysql select oldest record for each user

I'm trying to create a list in PHP of the oldest entries for each user in the database.
SELECT *,
MIN(`entries`.`entry_date`)
AS entry_date
FROM (`entries`)
JOIN `user_profiles`
ON `user_profiles`.`user_id` = `entries`.`user_id`
WHERE `status` = 1
GROUP BY `entries`.`user_id`
I'm using the query to retrieve from the entries table the oldest dated entry using MIN()and joining with table user_profiles for other data. The query should select the oldest entry for each user. It seems to work but it retrieves the wrong entry_date field on some entries when I echo them. Please help, I can't spot what I'm doing wrong..
You need to use a subquery to obtain the (user_id, entry_date) pairs for each user, then join that with a query that selects the records of interest:
SELECT *
FROM entries
NATURAL JOIN (
SELECT user_id, MIN(entry_date) AS entry_date
FROM entries
GROUP BY user_id
) AS tmin
JOIN user_profiles USING (user_id)
WHERE status = 1
Have you tried approaching the problem from the user_profiles table instead of the entries table? If a user has no entries, they will not appear in the above query.
This may help, but I'm not sure if it's the full solution:
SELECT *, MIN(entries.entry_date) as entry_date
FROM user_profiles LEFT JOIN entries USING (user_id)
WHERE status = 1
GROUP BY user_profiles.user_id
Also, you're renaming the MIN(entires.entry_date) as entry_date... but you already have a column named entry_date. Try renaming the derived columns to something unique like "min_entry_date"?

Basic MySQL question: how to get rows from one table that are not in another table?

I have a list of usernames (with a column called "username") + other info in my "users" table.
I also have another list of usernames (with a column called "username") in my smaller "recentusers" table.
How can I create a mysql query to get all the usernames that are in the "users" table but not in the "recentusers" table?
I know it is probably very simple, but any help would be appreciated!
select username from users where username not in (select username from recentusers)
Then after the first username add in the other information you want to select as well.
As pointed out by OMG Ponies, this query will run as fast as using Left Join or Is null.
The NOT IN keyword should be helpful :
SELECT username
FROM users
WHERE username NOT IN (
SELECT username
FROM recentusers
)
SELECT * FROM users
LEFT JOIN recentusers USING (username)
WHERE recentusers.username IS NULL;
You can also use a left join (which will perform faster than a subquery):
SELECT
users.username
FROM
users LEFT JOIN recentusers
ON users.username = recentusers.username
WHERE
recenterusers.username is null
Joins should be faster than subqueries, though I do not really know if mysql supports this.
select * from users
left outer join recentusers
on users.key = recentusers.key

Categories