MySQL insert data from other table - php

This question is similar to my previous question except this is INSERT instead of update
I have two tables: contacts and companies.
contacts has : id, group_id, company_id, email, company
companies has: id, group_id, name, email
so using this query
UPDATE contacts c
INNER JOIN companies co ON c.company_id = co.id
SET c.group_id = co.group_id,
c.company = companies.name
I can move update data from company to contacts where there contact.company_id = company.id.
But how can I do INSERT instead for all the company where does not have contact yet? or to make things simpler, how can I move all companies table data into contacts table data. e.g:
Companies
id group_id name email
1 1 abc a#a.com
2 1 def d#d.com
3 1 ghi g#g.com
Contacts
id group_id company_id email company phone
1 1 1 a#a.com abc
2 1 2 d#d.com def
3 1 3 g#g.com ghi
So I would like the entry like that, and for the one that is no value will be default to NULL or None

I think that you want:
INSERT INTO Contacts (id,group_id,company_id,email,name)
SELECT co.id,co.group_id,co.id,co.email,co.name
FROM company co
LEFT JOIN contacts c ON co.id = c.company_id
WHERE c.company_id IS NULL
This will insert all the information from contacts in company that wasn't already there. the column phone will be left null, since there is no information in contacts for that column.

I believe you would need to do an outer join between the 2 tables in your select statement then look for a field in your destination table to be null and only select those rows.
insert into t1 (f1,f2,f3) select s1,s2,s3 from sourcetable as st
left outer join t1 on
t1.f1=st.s1,
t1.f2=st.s2,
t1.f3=st.s3
where t1.id is null;
This way you only get the rows from st where there is no id in t1.

Related

How to select data according to if else condtion in mysql

I have three tables and i am getting incorrect result after query,Here is my table
Here is table "notifications"
id userId shopId notificationFor cretedOn
1 NULL 3 vendor 2020-07-23 09:01:12
2 152 3 vendor 2020-07-22 19:03:40
3 NULL 3 vendor 2020-07-22 09:20:56
Here is my table "users"
id first_name last_name createdOn
152 abc xyz 2020-06-11 14:53:27
Here is my table "shop"
id first_name last_name
3 hdh jyt
Now i want
All notification record where shopId='3'
AND i want in "notification" table if userId is NULL then fetch first_name and last_name from
"shop" table otherwise fetch "first_name" and "last_name" from "users" table
How can i do this ?
Unions can be bad for performance, but necessary at times. This is a potential solution:
select s.first_name, s.last_name
from notifications n join shop s on (n.shopId = s.id)
where userId is null
UNION
select u.first_name, u.last_name
from notifications n join users u on (n.userId = u.id)
where userId is not null;
SELECT notifications.id, notifications.notificationFor, (
CASE
WHEN notifications.userId IS NULL
THEN CONCAT(shop.firstName, shop.lastName)
ELSE CONCAT(users.firstName, users.lastName)
END
)
as customerName
FROM `notifications` JOIN shop ON shop.id = notifications.shopId
LEFT JOIN users ON users.id = notifications.userId
WHERE notifications.shopId=3
Note the LEFT JOIN is used on users table.

cross referencing tables and inserting the results into another table SQL

So i have 3 tables that are like the following:
table 1 - cats - that has the following structure:
id name plural_name
0 painters painters
1 builders builders
table 2 - places - that has the following structure
place_id place_name classification
243 painter comp painters
230 builder comp builders
table 3 - rel_place_cat - that has the following structure
id place_id cat_id
0 243 0
1 230 1
So basically i need to run an SQL command to find to find the category id number in table 1 and the place_id from table 2 and insert the data into table 3
can this be done ?
Thank you
If you want to make that insert also repeatable?
Then you could also join to the relation table.
And only insert the missing relations.
Example query:
INSERT INTO rel_place_cat (place_id, cat_id)
SELECT p.place_id, c.id
FROM cats c
JOIN places p ON p.classification = c.plural_name
LEFT JOIN rel_place_cat r ON (r.place_id = p.place_id AND r.cat_id = c.id)
WHERE r.id IS NULL
GROUP BY p.place_id, c.id;
Not sure if joining the "classification" to "plural_name" or to "name" would be better.
In the sample they are the same anyway.
But those values in "classification" are all plural, so "plural_name" was used for the join.
Something like:
insert into table3(place_id, cat_id)
select place_id, cat_id
from(select place_id, cat_id
from table1
inner join table2 on table1.name = table 2.classification)
Should work.

Or condition in INNER JOIN

I have a table structured as follows (points):
id1 | id2 | p1 | p2
1 3 5 7
3 1 2 4
1 2 1 7
And another table strucuted as follows (users):
id | name
1 User1
2 User2
3 User3
So now, I need a query that specifing an ID (for example 3), the query check that the ID appears in the column id1 and id2, and if it appears in one of the two columns, it gives me back the user name with id1 and id2 from the rows selected. So, for example if I specific the ID 3, the query give me back:
name1 | name2 | p1 | p2
User1 User3 5 7
User3 User1 2 4
I tried various solutions but no way to do it, I think that I need an OR condition in the INNER JOIN but I don't know if it's possible and if it's the solution.. I didn't find nothing here.
I mean something like:
INNER JOIN users ON (users.id = points.id1) || (users.id = points.id2)
Any solution for that? Thanks
Join the user table twice:
SELECT u1.name, u2.name, p.p1, p.p2
FROM points p
JOIN users u1 ON u1.id = p.id1
JOIN users u2 ON u2.id = p.id2
WHERE u1.id = 3 OR u2.id = 3
Use case statement it will give you all matching value not need restricted for one or two values
CREATE TABLE points (id1 int(2), id2 int(2), p1 int(2), p2 int(2));
INSERT INTO points VALUES(1,3,5,7);
INSERT INTO points VALUES(3,1,2,4);
INSERT INTO points VALUES(1,2,1,7);
CREATE TABLE users (id int(2), name char(23));
INSERT INTO users VALUES(1,'user1');
INSERT INTO users VALUES(2,'user2');
INSERT INTO users VALUES(3,'user3');
SELECT (CASE WHEN u.id = p.id1 THEN u.name END) AS name1,
(CASE WHEN u1.id = p.id2 THEN u1.name END) AS name2,
p1, p2
FROM points p
INNER JOIN users u ON (u.id = p.id1)
INNER JOIN users u1 ON (u1.id = p.id2);

SQL Query based on value of a different row

I'm trying to query data from multiple tables but cannot seem to achieve this type of JOIN. For example, I have one table with contains products, and a wp_usermeta table with various user meta data:
Products Table
Serial # Product
---------------------
0001 A
0002 B
0003 C
wp_usermeta (simplified)
User ID Key Value
--------------------------------
1 Serials 0001
1 Company Company A
2 Serials 0001
2 Company Company B
3 Serials 0001
3 Company Company C
I need to get the Company name based on the serial numbers they own, such as:
Serial # Company
-------------------------
0001 Company A
0002 Company B
0003 Company C
I've been able to retrieve the User ID based on serial number with a simple join query, but I dont know where to go from there.
SELECT products.serial_number, wp_usermeta.user_id FROM products LEFT JOIN wp_usermeta ON products.serial_number = wp_usermeta.meta_value
I am not sure what the products table has to do with the results you need.
One method is a "simple" self-join:
SELECT p.value as serial_number, c.value as Company.user_id
FROM wp_usermeta p JOIN
wp_usermeta c
ON p.user = c.user AND
p.key = 'Serials' AND
c.key = 'Company';
You need 2 joins on wp_usermeta like this:
SELECT Products.Serial, w2.Value AS Company
FROM Products
# Detect User Id by serial number
JOIN wp_usermeta w1 ON w1.Key = 'Serials'
AND w1.Value = Products.Serial
# And select company by detected User Id
JOIN wp_usermeta w2 ON w2.Key = 'Company'
AND w2.User = w1.User

Mysql joints is possible?

I have two table one table containing station id and station name, and another table containing id, name, startStationId, endStationId. I know second table's id by using that id i need to fetch all details of second table with station name for corresponding startStationId, endStationId.
ex: table1
---------------------------------
slNo staionId staionName
---------------------------------
1 0012 Bangalore ,
2 0014 Chennai ,
3 0015 Mumbai
---------------------------------
Table 2:
------------------------------------------
Id Name startStationId endStationId
-------------------------------------------
123 Dhinesh 0014 0015
-------------------------------------------
For example i know second table id(123).. so i want to fetch all results by using id, result would be.
Id =>123, Name => Dhinesh, StartStaion =>Chennai , Endstation=>Mumbai.
How can we write in one single query...?
Thanks in advance.
Try this.
SELECT t2.Id,t2.name,t1.StationName,t3.StationName
FROM table2 t2
INNER JOIN table1 t1 ON t2.startStationId = t1.stationId
INNER JOIN table1 t3 ON t2.endStationId = t3.stationId
SELECT t2.Id, t2.Name, tstart.stationName , tend.stationName
FROM table2 as t2
INNER JOIN table1 as tstart ON t2.startStationId = tstart.stationId
INNER JOIN table1 as tend ON t2.endStationId = tend.stationId
this should work

Categories