Combine two mysql tables with companies and contacts - mysql

i have two tables in mysql. The first one holds companies and the second one holds contacts that work for these companies.
There are companies without contacts, and there are several contacts that can work for one company, but there are never contacts without a company.
The tables look like this:
company table
company_id
company_name
company_telephone
contacts table
contact_id
works_for_company_id
contact_fullname
contact_telephone
I am trying to combine both tables with one select statement in order to create a list of telephone numbers for each and every entry, e. g. one company with two contacts results in three entries, each with the company name and telephone number in one row.
I tried JOIN statements, which all resulted in displaying the contacts but not the companies behind it, i tried UNION (didn't work because of different column names). What else am I missing? Any help would be appreciated.

You combine both join and union - but you will have to rename the differently named columns (via AS):
SELECT company_id, company_telephone AS phone FROM company
UNION
SELECT company_id, contact_telephone AS phone FROM company JOIN contacts ON ...

All you need is direct straight join to get all the details. You can replace * with relevant column names:
SELECT *
FROM CONTACTS_TABLE con
JOIN COMPANY_TABLE cta ON cta.company_id = con.works_for_company_id

As people told you in previous comments, you need a join/inner join
SELECT comp.company_id, cont.contact_fullname
FROM company comp
INNER JOIN contacts cont ON comp.company_id = cont.works_for_company_id;

There are companies without contacts SO you need to use LEFT JOIN
SELECT com.company_name,com.telephone ,com.company_id, con.contact_fullname
FROM company com
LEFT JOIN contacts con ON com.company_id = con.works_for_company_id;

The UNION operator is used to combine the result-set of two or more SELECT statements.
Each SELECT statement within UNION must have the same number of
columns
The columns must also have similar data types
The columns in each SELECT statement must also be in the same order
SELECT company.company_name, company.company_telephone
FROM company
WHERE company.company_id =1
UNION
SELECT contact.contact_fullname, contact.contact_fullname
FROM company
JOIN contact ON company.company_id = contact.works_for_company_id
WHERE company.company_id =1
LIMIT 0 , 30

Related

Joining tables in MySQL and requesting data from second table only

I'm trying to join 2 tables where I need to show only 3 columns from the second one where another column is used as a comparison.
For example:
Table one is called employee: it has a column called user_id and some other columns
Table two is called people: it has a column called user_id which included some of the employees user_ids
The columns I want to select are all from table people! (firstname, lastname, email)
I tried the following but something going wrong:
SELECT userid, firstname, lastname, email
FROM people
JOIN employee
WHERE people.userid = employee.userid;
I'm not sure what am I doing wrong, could you please help me correct it?
You can try this query:
SELECT
p.userid,
p.firstname,
p.lastname,
p.email
FROM
people as p,
employee as emp
WHERE
p.userid = emp.userid
Looking at your script, it looks like you'll run into ambiguous columns in at least your userid. You want to explicitly tell SQL where the column comes from like in your WHERE clause if there are columns sharing the same name between the two tables.
SELECT
userid, -- AMBIGUOUS
firstname,
lastname,
email
FROM people
JOIN employee
WHERE people.userid = employee.userid;
Example solution:
SELECT
people.userid,
people.firstname,
people.lastname,
people.email
FROM people
JOIN employee
WHERE people.userid = employee.userid;
For this issue you can use this query
let suppose that I have a users table where a user have zero to one profile picture
I need the user (Name,LastName,BirthDate) for users who have no profile picture
I can use this query
select *
from user c
where NOT EXISTS (
select 1
from photo p
where p.id = c.photo_id
)
in this where you can use any field between this two table
removing the not will result on the users who have a profile picture
hope this help you
you can search for SEMI JOIN and ANTI JOIN for more informations
i think this query will solve your problem
insert into table1 (clmn_1,clmn_2,clmn_3) SELECT clmn_1,clmn_2,clmn_3 FROM table2 where id = value

How to join on conditional tables

I have to maintain a database that has 3 different tables for their users (for different roles). Unfortunately, merging them is not allowed.
There is another table that logs their activity, and this table has two columns for identifying a specific user, one is userId, and the other is roleId. Now, when I want to list user activities for all users, then depending on the value in roleId, I would have to join each row with a different table.
If there was only one table with users, the query would be something like:
SELECT * FROM activity JOIN buyers ON activity.userId = buyers.id
So how would I expand on this query now, if I had 3 tables with users: buyers, sellers, and administrators; knowing that the roleId column in the activity table identifies either a buyer, a seller, or an administrator?
SELECT *, 'Buyer' as accountType FROM activity JOIN buyers b ON activity.userId = b.id
UNION
SELECT *, 'Seller' FROM activity JOIN sellers s ON activity.userId = s.id
UNION
SELECT *, 'Admin' FROM activity JOIN administrators a ON activity.userId = a.id
may consider writing the above as a view that way I could build on it as needed, given I can't change any existing table design.
may have to spell out specific table columns as well if buyer, seller, and admin have different columns. Given you've not provided the table structures, I'm assuming they are identical for this example purpose.
Just guessing here as to how roleId relates to the other tables.
SELECT * FROM activity JOIN buyers ON activity.userId = buyers.id
WHERE activity.roleId = 1
UNION SELECT * FROM activity JOIN sellers ON activity.userId = sellers.id
WHERE activity.roleId = 2
UNION SELECT * FROM activity JOIN administrators ON activity.userId = administrators.id
WHERE activity.roleId = 3

Query two tables with result opposite of join like statement

Here is the simple question to gain some medals :) :
I have three tables:
"contacts" that holds the contacts information where each entry has a unique id.
The second table "groups" where is stores the name for each group and the group id.
The last "contacts_groups" binds each contact to a group, it has just two columns, contact_id and group_id.
The question is how do write in a single statement a MySQL query that will select all contacts that are not assigned to a group. In other words contacts which id is not listed in "contacts_groups" table?
select * from contacts c
left outer join contacts_groups cg on c.id = cg.contact_id
where cg.contact_id is null
SELECT * FROM contacts c
WHERE NOT EXISTS (SELECT * FROM contacts_groups cg
WHERE cg.contact_id = c.contact_id)
Just to be complete, here's another solution:
SELECT * FROM contacts
WHERE contact_id NOT IN (SELECT contact_id FROM contacts_groups)
However, I think MySQL tends to execute the left join or correlated subquery more efficiently.

select data from two independent tables

I have two tables (MAILS & customers) in my MySQL db both having a column email storing email addresses.
Now I'd like to select every row from these two tables where emails.email!=customers.email.
When I do a simple SELECT * FROM emails, customers WHERE emails.email != customers.email, I get each emails.email listed with a data from the customers table.
How do I do that? Can I use DISTINCT but apply it only to the data coming from the customers table?
If you're wanting a unique list of email addresses found in either the emails table or the customers table where there is not a match between them on the email field this will do the trick:
SELECT DISTINCT COALESCE(e.Email, c.Email) as Email
FROM Emails e FULL OUTER JOIN Customers c ON e.Email = c.Email
WHERE e.Email IS NULL OR c.Email IS NULL
Coincidentally, this type of circumstance is one of the very few situations in which I have ever found the FULL OUTER JOIN to be of particular use...
A 'not-equals' join is very seldom helpful unless there is in fact another column that can be joined for equality. So, if you have a PersonID column in each of the two tables, then you can do:
SELECT m.*, c.*
FROM mails AS m
JOIN customers AS c ON c.PersonID = m.PersonID
WHERE c.email != m.email
But without that extra condition, you have what is close to a Cartesian Product of the two tables, where almost every row in one table is matched with almost every row in the other (because of the not equals condition). Without the not equals condition, the result set would be only slightly larger.

MySQL: Selecting from 3 tables

I have the following query:
SELECT
DISTINCT sites.site_id,
sites.site_name,
sites.site_url,
earnings.cust_id
FROM
sites,
earnings
WHERE sites.site_id = earnings.site_id AND sites.site_id IN('8', '1666')
That query gives me very well the information asked. It returns two rows, one for site 8 and another for site 1666, with the information on them from those tables.
Now, I want that the cust_id number be used to select from another table (let's say table customers) where they are stored by id and where other info is such as name, last name, etc.
Basically what I need is to expand that query to extract customer name and last name from the table customers, using the ids obtained.
Same way you got the info from two tables. Add a comma, add the third table name, and add the relationship to your WHERE clause like you did with the first two tables.
SELECT
DISTINCT sites.site_id,
sites.site_name,
sites.site_url,
earnings.cust_id,
customers.name,
customers.last_name
FROM
sites,
earnings,
customers
WHERE sites.site_id = earnings.site_id AND sites.site_id IN('8', '1666') AND customers.id = earnings.cust_id
I think it's clearer to write out the JOINs though:
SELECT
sites.site_id,
sites.site_name,
sites.site_url,
earnings.cust_id,
customers.name,
customers.last_name
FROM
sites
INNER JOIN
earnings
ON
earnings.site_id = sites.site_id
INNER JOIN
customers
ON
customers.id = earnings.cust_id
WHERE
sites.site_id IN (8, 1666)
GROUP BY
sites.site_id