SQL - re-arrange a table via query - sql

I have a poorly designed table that I inherited.
It looks like:
User Field Value
-------------------
1 name Aaron
1 email aaron#company.com
1 phone 800-555-4545
2 name Mike
2 email mike#group.org
2 phone 777-123-4567
(etc, etc)
I would love to extract this data via a query in the more sensible format:
User Name Email Phone
-------------------------------------------
1 Aaron aaron#company.com 800-555-4545
2 Mike mike#group.org 777-123-4567
I'm a SQL novice, but have tried several queries with variations of Group By,
all without anything even close to success.
Is there a SQL technique to make this easy?

this not a 'badly designed table'; but in fact an Entity Attribute Value (EAV) table. unfortunately, relational databases are poor platforms to implement such tables, and negate most of the nice things of RDBMS. A common case of using the wrong shovel to nail in a screw.
but i think this would work (based on Marcus Adams' answer, which i don't think would work (edit: now it does))
SELECT User1.Value AS name, User2.Value AS email, User3.Value AS phone
FROM Users User1
LEFT JOIN Users User2
ON User2.User = User1.User AND User2.Field='email'
LEFT JOIN Users User3
ON User3.User = User1.User AND User3.Field='phone'
WHERE User1.Field = 'name'
ORDER BY User1.User
Edit: got some niceties from other answers (LEFT Joins, and the field names on the ON clauses), now does anybody know how to put the remaining WHERE a little higher? (but not on the first JOIN's ON, that's too ugly), of course it doesn't matter since the query optimizer uglyfies it back anyway.

At my work we are unfortunate to have a database design like this. But this kind of design works better for us then a traditional database design because of the different records we have to store and gives us the flexibility that we need. The database that we are using stores millions of records.
This would be the fastest way to run the query on a large database using MSSQL. It saves from having to do as many joins which could be very costly.
DECLARE #Results TABLE
(
UserID INT
, Name VARCHAR(50)
, Email VARCHAR(50)
, Phone VARCHAR(50)
)
INSERT INTO #Results
SELECT DISTINCT User FROM UserValues
UPDATE
R
SET
R.Name = UV.Value
FROM
#Results R
INNER JOIN
UserValues UV
ON UV.User = R.UserID
WHERE
UV.Field = 'name'
UPDATE
R
SET
R.Email = UV.Value
FROM
#Results R
INNER JOIN
UserValues UV
ON UV.User = R.UserID
WHERE
UV.Field = 'Email'
UPDATE
R
SET
R.Phone = UV.Value
FROM
#Results R
INNER JOIN
UserValues UV
ON UV.User = R.UserID
WHERE
UV.Field = 'Phone'
SELECT * FROM #Results

You can use a self join:
SELECT User1.User, User1.Value as Name, User2.Value as Email,
User3.Value as Phone
FROM Users User1
JOIN Users User2
ON User2.User = User1.User
JOIN Users User3
ON User3.User = User1.User
WHERE User1.Field = 'name' AND User2.Field = 'email' AND User3.Field = 'phone'
ORDER BY User1.User
I tested this query, and it works.

I believe this will build the result set you're looking for. From there, you can create a view or use the data to populate a new table.
select user, name, email, phone from
(select user, value as name from table where field='name')
natural join
(select user, value as email from table where field='email')
natural join
(select user, value as phone from table where field='phone')

In MySQL you can do something like this:
SELECT
id,
group_concat(CASE WHEN field='name' THEN value ELSE NULL END) AS name,
group_concat(CASE WHEN field='phone' THEN value ELSE NULL END) AS phone,
...
FROM test
GROUP BY id
The aggregate function actually doesn't matter, as long as you have only one field of each type. You could also use min() or max() instead with the same effect.

A variant of Javier's answer, which has my vote.
SELECT
UserName.name, UserEmail.email, UserPhone.phone
FROM
Users AS UserName
INNER JOIN Users AS UserEmail ON UserName.User = UserEmail.User
AND UserName.field = 'name' AND UserEmail.field = 'email'
INNER JOIN Users AS UserPhone ON UserName.User = UserPhone.User
AND UserPhone.field = 'phone'
Use LEFT JOINs if not all attributes are guaranteed to exist. A composite index over (User,Field) would probably be beneficial for this.

Related

trouble with inner joining 2 tables

I have a database with 2 tables in it one is 'enlistments' and the other one is 'users'. In the enlistments table I have a user_id and in the users table I have a name. I want to get the name of the user which belongs to the id.
I know I need to do this with an inner join like this:
SELECT enlistments.round_id, users.name
FROM enlistments
INNER JOIN users
ON enlistments.user_id=users.name
WHERE enlistments.activity_id = 1;
However I get this error: Warning: #1292 Truncated incorrect DOUBLE value
I did some research and found out it has to do with comparing an int with a string but I don't know how to solve the problem.
This is how my database looks like
join on is the condition you use to join the tables. Here it's enlistments.user_id=users.id.
select e.round_id
,u.name
from enlistments e join users u on u.id = e.user_id
where activity_id = 1
round_id
name
1
test2
Fiddle
To validate and be sure you are pulling back the exact data desired, I usually provide aliases for each column brought back and make sure to bring back the join columns also. It's good practice to label where the columns returned originated.
SELECT
Enlistments.UserID as Enlistments_UserID,
Users.ID as Users_ID,
enlistments.round_id as Enlistments_RoundID,
users.name as Users_Name
FROM enlistments
INNER JOIN users
ON enlistments.user_id=users.id
WHERE enlistments.activity_id = 1;
SELECT EN.round_id, US.name
FROM enlistments EN
INNER JOIN users US
ON US.name= CAST(EN.user_id AS VARCHAR)
WHERE EN.activity_id = 1
What you are needing is the function cast that can convert any kind of data into another, so you'll pass your integer value as the first argument followed by "AS '%DATATYPE'" where %DATATYPE is the kind of data you want to achieve.
In your case:
SELECT CAST(123456 AS VARCHAR)
-- RETURNS : '123456'
Anyway, I’m not sure that you can be able to join these two tables with the join you are using.
For more help please share some data.

Oracle SQl Dev, display id, firstname, surname and users number of files

I am trying to write a query in oracle sql developer that will list
UNum, FirstName, Surname, and the number of files the users has, if the user has 0 it should be displayed as 0 next to their name.
(PK) = Primary Key
(FK) = Foreign Key
The database schema is as follows:
Building(buildingNum(PK), Description, instname, buildName, state, postcode)
User(UNum(PK), buildingNum(FK), Surname, FirstName, initials, title)
File(FileNum(PK), title)
UserAccount(FileNum(PK)(FK), UNum(PK)(FK))
Job(JobNum(PK), id, title)
Interest(JobNum(PK)(FK), UNum(PK)(FK), Description)
So far i have tried the following block of code:
Select User.UNum, User.FirstName, User.Surname, Count(UserAccount.FileNum)
from User, UserAccount
where User.UNum = UserAccount.UNum
group by User.UNum, User.FirstName, User.Surname;
I end up with the result being a long list of Users made up of UNum, FirstName and Surname followed by the number of files they have, however none of the results return with a 0. the list also seems to be extremely long for the size of the database. How do i find those who also have 0 files and is there anything else im doing wrong? expected result should be a much shorter list of users including those who don't have any files (There are 7 people in the database with 0 files) Thanks.
You want a left join:
Select u.UNum, u.FirstName, u.Surname,
Count(ua.FileNum)
from User u left join
UserAccount ua
on u.UNum = ua.UNum
group by u.UNum, u.FirstName, u.Surname;
This also introduces table aliases, which makes it simpler to write and read the queries.
You can also write this using a correlated subquery:
select u.UNum, u.FirstName, u.Surname,
(select count(ua.FileNum)
from UserAccount ua
where u.UNum = ua.UNum
)
from User u;
This version might have somewhat better performance.
You want a left join. That keeps rows from the table left of the join operator even if no matching row is found in the table right to it.
SELECT user.unum,
user.firstname,
user.surname,
count(useraccount.filenum)
FROM user
LEFT JOIN useraccount
ON useraccount.unum = user.unum
GROUP BY user.unum,
user.firstname,
user.surname;

SQL SELECT * FROM 2 tables

I am building a small database app for friends where table 1 is contacts and table 2 is users. I can find email on both (One as the loggued in user and the other as the owner of the contact)
SELECT *
FROM contacts
WHERE contacts.username = users.email
I try to show all contacts fields where username is equal to already loggued in users (email)
Thanks you very much!
It sounds like you're trying to JOIN two tables together. Ideally, you don't want to use the email as the primary key on a table (the smaller the data, the faster your JOIN will be); a better option would be to add an auto-incrementing Id (integer) to both the Contacts and Users tables, set as the primary key (unique identifier). Joining on integers is much faster, as integers are 4 bytes per row, vs string which (in MySQL) is 1 per character length (latin1 encoding) + 1 byte.
Anyway, back to the original question. I believe the query you're looking for (MySQL syntax) is:
SELECT c.Id, c.Col1, u.Col2, ...
FROM contacts AS c
INNER JOIN users AS u ON u.email = c.username
Additionally, I would avoid the use of *, as it slows down the query a bit. Instead, try to specify the exact columns you need.
Try the following. Also, I would suggest you learn about joins in SQL.
SELECT *
FROM contacts
INNER JOIN
users on contacts.username = users.email
Use Inner Join:
SELECT *
FROM contacts as c
INNER JOIN
users as u on u.email = c.username

Using Join to parse out duplicate data

I am having a bit of a problem here with this statement below using tables:
[Users] Name,Email,Subscribed
[Email] Name,Email,Subscribed
Basically what needs to be accomplished is all the Subscribed Users in the Users table need to be checked against the users in the Email table to see if they exist in the table or not, and only return the users in the Users table which are not found in the Email table.
Here is the statement I've used, but it returns millions of rows and takes forever, and it is returning every email address in the Email table, I don't think this is the best way to approach this issue because it is not returning accurate data. Any thoughts?
SELECT Distinct c.Name,c.Email from Users c
INNER JOIN Email e on c.Email <> e.Email
WHERE c.Subscribed=1
I think this is what you are looking for.
SELECT c.Name,c.Email
FROM Users c LEFT JOIN Email e ON (c.email=e.email)
WHERE (e.email is null) and (c.subscribed=1)
The INNER JOIN in your query with no ON clause is why you are getting wacky results.
change the <> to =
You are doing an join on non-equality so that is why your result size is exploding.
On a side note - check into foreign keys going forward - they make this type of cross table referential integrity a non-issue.
UPDATE - if you want results in one table that are not in the other do:
select * from table1 where email not in (select distinct email from table2);
This will give you all the records in table1 that don't match an email in table 2.
HTH
You will want to use a LEFT JOIN to accomplish this:
SELECT Distinct u.Name, u.Email
FROM Users AS u
LEFT JOIN Email AS e ON u.Email = e.Email
WHERE e.Email IS NULL
AND u.Subscribed = 1
Graphical explanation of JOINS may be helpful
I strongly recommend using Foreign Keys to maintain referential integrity.

SQL Update one table comparing info from two tables

I have the following problem:
Let's suppose I defined TWO tables
USERS
ID (int. key)
NAME (String)
SALARY (currency)
USERSADD
ID (int. key)
TYPE (String)
The 2nd table stores additional information for USERS. Obviously the real tables are more complicated but this is the idea. (Don't ask me why another table is created instead of adding fields to the first table, this is my boss's idea).
Now I am trying to UPDATE the first table if a condition from second table is satisfied.
Something like this:
UPDATE USERS U, USERSADD A
SET U.SALARY = 1000
WHERE U.ID = A.ID
AND A.TYPE = 'Manager'
In Netbeans Derby I have an error: ", found in column X", and it refers to the comma between the two tables (UPDATE USERS U, USERSADD A). I hope I was clear enough...
Would somebody be kind enough to provide me with a solution? Thanks in advance.
UPDATE USERS
SET SALARY = 1000
WHERE ID IN (
SELECT ID FROM USERSADD
WHERE TYPE = 'Manager')
UPDATE USERS
SET USERS.SALARY = 1000
FROM USERS JOIN USERSADD ON USERS.ID = USERSADD.ID
WHERE USERSADD.TYPE ='MANAGER'
The syntax you are using uses an implicit INNER JOIN. It would be better for you to use an explicit join. Try something like this:
UPDATE Users
SET Salary = 1000
FROM Users u
INNER JOIN Usersadd a on u.id=a.id
AND a.Type = 'Manager
UPDATE USERSU
SET SALARY = 1000
WHERE exist IN (
SELECT ID
FROM USERSADD A
WHERE TYPE = 'Manager'
AND U.id = A.id
)