Insert (join of two tables) into a different table - php

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

Related

How to build table from two tables, one with useless unique identifier (WordPress wp_usermeta table)

Use case background: I'm using a WordPress site to manage memberships, and the ID Card software on my PC will connect to a table to generate its information. It can connect to only one table.
Goal: I need a table called "id_card" that contains the columns (member_number, first_name, last_name, exp_date), and it's populated with users that have been modified within the last month ("membership" table has a column titled "moddate" that I can use as the criteria).
Challenge 1: I need to pull exp_date from table "membership" and the other values -- member_number, first_name, last_name -- all come from a table called "wp_usermeta" (a default table for WordPress). Both source tables contain user_id to associate the information to the same user account. I believe this requires some kind of LEFT JOIN, but I haven't been able to get it to work.
Challenge 2: the bigger challenge: wp_usermeta table contains all the different user attributes in ROWS instead of COLUMNS. So the columns are titled "user_id, meta_key, meta_value" and there might be 30 rows for a single user. If I want to SELECT user 49's first name, it looks something like this:
SELECT meta_value FROM wp_usermeta WHERE user_id=49 AND meta_key='first_name'
Question: How do I write this query so it will INSERT INTO the table "id_card" the values from the two tables, using the user_id to keep it all lined up, especially when I can't use solely the user_id as a unique identifier (i.e. the only way I know to narrow it down to someone's first name is use both their user_id and the meta_key) in the wp_usermeta table?
There is a major problem with your wanting to copy data. If the user changes their data then your copy will be out of date. If you look at the wp_users table there is a ID field. This points to the relevant entries in the wp_usermeta table (user_id)
SELECT `wp_users`.*
, `wp_usermeta`.*
FROM `wp_users`
INNER JOIN `wp_usermeta` ON (`wp_users`.`ID` = `wp_usermeta`.`user_id`)
WHERE ID=1;
Now this will return multiple rows. If you want a single record then you'll need to do
SELECT`wp_users`.*
, (SELECT meta_key FROM wp_usermeta WHERE meta_key='wp_user_level' AND user_id=1) AS user_level
, (SELECT meta_key FROM wp_usermeta WHERE meta_key='show_syntax_highlighting' AND user_id=1) AS syntax_highlighting
FROM `wp_users`
WHERE ID=1;
Just repeat the subquery statements for as much info that you want to return. The subquery can only return a single value.

Comparing sql tables and

I want to know how to compare two tables, and if they have the same values show them.
My original table is user_information, and there are 30 other tables with different names, but all of them have
the same columns which are email, name and website.
How to compare user_information table with all the other 30 tables automatically and that includes any new table I will add later.
What you need is basically this (sql-server):
Select email, name, website from table1
intersect
Select email, name, website from table2 ....
And so on.
Should do the trick.
If you're running the query against a MySQL database:
SELECT DISTINCT email, name, website FROM table1
INNER JOIN table2
USING (email, name, website);

php Mysql avoid insert into duplicate entries

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'

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.

"Conditional" Join Based on Field Value?

The site I'm working on has 3 different types of users: admin, applicants, reviewers. Each of these groups will have some basic info that will need to be stored (name, id, email, etc) as well as some data that is unique to each. I have created a users table as well as a table for each of the specific groups to store their unique data.
users: id, f_name, l_name, email, user_type
users_admin: id, user_id, office, emp_id
users_applicant: id, user_id, dob, address
users_reviewer: id, user_id, active_status, address, phone
If a user with user_type of "1" (applicant) logs in I will need to JOIN to the users_applicants table to retrieve their full record. I tried using a UNION but my tables have vastly different columns.
Is there a way to, based on a user's type, write a conditional query that will JOIN to the correct table? Am I going about this completely the wrong way?
Thank's in advance for your help!
Well, in the end your tables are already flawed. Why even have a table for each type? Why not put all those fields into the users table, or maybe a user_details table (if you really want an extra table for non-general data fields)? Currently, you're actually creating 4 independent user tables from a relational point of view.
So why do the type-tables have a surrogate key? Why isn't the user_id already the (only) primary key?
If you changed that, all you would need is the user id to retrieve the data you want, and you've already got that (or you wouldn't even be able to retrieve the user type).
Either you do it programmatically, or you can do this with a series of CASEs and LEFT JOINs.
For simplicity's sake let's do this with a table users where you can have a user of type 1 (normal user), 2 (power user) or 3 (administrator). Normal users have an email but no telephone, power users have an address and a field dubbed "superpower", and administrators have a telephone number and nothing else.
Since you want to use the same SELECT for all, of course you need to place all these in your SELECT:
SELECT user.id, user.type, email, address, superpower, telephone
and you will then need to LEFT JOIN to recover these
FROM user
LEFT JOIN users_data ON (user.id = users_data.user_id)
LEFT JOIN power_data ON (user.id = power_data.user_id)
LEFT JOIN admin_info ON (user.id = admin_info.user_id)
Now the "unused" fields will be NULL, but you can supply defaults:
SELECT
CASE WHEN user.type = 0 THEN email ELSE 'nobody#nowhere.com' END AS email,
CASE WHEN user.type = 1 OR user.type = 2 THEN ... ELSE ... END as whatever,
...
Specific WHERE conditions you can put in the JOIN itself, e.g. if you only want administrators from the J sector, you can use
LEFT JOIN admin_info ON (user.id = admin_info.user_id AND admin_info.sector = 'J')
The total query time should not be too bad, seeing as most of the JOINs will return little (and, if you specify a user ID, they will actually return nothing very quickly).
You could also do the same using a UNION, which would be even faster:
SELECT user.id, 'default' AS email, 'othermissingfield' AS missingfieldinthistable,
... FROM user JOIN user_data ON (user.id = user_data.user_id)
WHERE ...
UNION
SELECT user.id, email, 'othermissingfield' AS missingfieldinthistable,
... FROM user JOIN power_data ON (user.id = power_data.user_id)
WHERE ...
UNION
...
Now, if you specify the user ID, all queries except one will fail very fast. Each query has the same WHERE repeated plus any table-specific conditions. The UNION version is less maintainable (unless you generate it programmatically), but ought to be marginally faster.
In all cases, you'll be well advised in keeping updated indexes on the appropriate fields.
Instead i will suggest you reconstruct you tables structure like this.
Create a table
users_types :
id
type
Then create another table users with a foreign key
users :
id
f_name
l_name
email
office
emp_id
dob
address
active_status
phone
users_types_id
And now when you need to insert data insert null in the fields which are not required for a particular user. And you can simply fetch records on the basis of id. Also using left join will give you the name of user type.

Categories