Insert data in table using two or more tables - mysql

I have two existing table and wants to create third table with help of few columns. The fist two tables are;
Table one: users
|id | name | sid |
| 1 | demo | test1 |
| 2 | anu | test2 |
Table one: insights
| id | description| name |
| 1 | yes | demoone|
| 2 | no | demotwo|
I want to insert data in new table called insight_owner. As per my knowledge, I made below query but that is giving me below error
ERROR 1242 (21000): Subquery returns more than 1 row
The query used is
insert into insight_owner (column_one, column_two, column_three, column_four, column_five) VALUES ('1', '0', NULL, (select u.id from users u where u.sid='test1'), (select i.id from insights i)) ;
Expected output is
| column_one| column_two| column_three| column_four| column_five| column_six |
+----+-----------------+--------------------+---------------+-----------+--------------------+
| 1 | 1 | 1 | NULL | 1 | 1 |
| 2 | 1 | 1 | NULL | 1 | 2 |
column_five = Users id
column_six = Insight id

INSERT...SELECT syntax is what you're looking for (instead of INSERT...VALUES, which is limited to single values per column in each value list). That allows you to select the data directly from the table(s) concerned, using normal SELECT and JOIN syntax. You can also hard-code values which you want to appear on every row, just as you can in a normal SELECT statement. Basically, write the SELECT statement, get it to output what you want. Then stick an INSERT at the start of it and it sends the output to the desired table.
insert into insight_owner (column_one, column_two, column_three, column_four, column_five)
select '1', '0', NULL, (select u.id from users u where u.sid='test1'), i.id
from insights i

You are using
insert into insight_owner (column_one, column_two, column_three, column_four, column_five) VALUES ('1', '0', NULL, (select u.id from users u where u.sid='test1'), (select i.id from insights i));
Which basically inserts one row in your new table.
So, when you add subquery
select i.id from insights i
It will return all rows from insights table an you actually want just one value.
The result you will get is
| id |
| 1 |
| 2 |
And you want
| id |
| 1 |
So, you should be adding conditional that will make sure you are getting only one result as you are doing with first query (where u.sid='test1'), or limit.
I hope this helps.

Related

MYSQL Using multiple selects in insert query is returning Column count doesn't match value count at row 1

UPDATE
Sometime, when a family is being inactivated from a system, it may contain more than 1 individual. In my case show at the sql fiddle, the family with household_id=12 has 3 individuals.
I need to insert the data of these 3 individuals as the same from indiviudal table to individual_history table and just changing the ind_action field into the following message HH has been inactivated.
Here is a sample data:
| individual_id | household_id | family_relation_id | marital_status_id | ind_lmms_id | ind_un_id | head_of_hh | ind_first_name_ar | ind_last_name_ar | ind_first_name_en | ind_last_name_en | ind_gender | dob | ind_status | ind_date_added | user_id | system_date |
|---------------|--------------|--------------------|-------------------|-------------|-----------|------------|-------------------|------------------|-------------------|------------------|------------|------------|------------|----------------------|---------|----------------------|
| 1 | 12 | 3 | 1 | 321 | (null) | no | u | x | (null) | (null) | Male | 2012-01-01 | Active | 2018-07-19T00:00:00Z | 1 | 2018-07-19T00:00:00Z |
| 2 | 12 | 1 | 2 | 123 | (null) | no | x | y | (null) | (null) | Female | 1998-03-05 | Active | 2015-03-05T00:00:00Z | 1 | 2015-03-05T00:00:00Z |
| 3 | 12 | 3 | 1 | 1234 | (null) | no | x | z | (null) | (null) | Female | 2004-04-05 | Active | 2018-04-11T00:00:00Z | 1 | 2018-04-11T00:00:00Z |
All 3 fields should be inserted to the table individual_history and ind_action is set to the note I added above.
I need to insert into a table called individual_history values of a SELECT query from table individual.
Here is the query:
INSERT INTO individual_history
(individual_id,
household_id,
family_relation_id_history,
marital_status_id_history,
ind_lmms_id_history,
ind_un_id_history,
head_of_hh_history,
ind_first_name_ar_history,
ind_last_name_ar_history,
ind_first_name_en_history,
ind_last_name_en_history,
ind_gender_history,
dob_history,
ind_status_history,
ind_action,
ind_date_changed,
user_id,
system_date)
VALUES ((SELECT i.individual_id,
i.household_id,
i.family_relation_id,
i.marital_status_id,
i.ind_lmms_id,
i.ind_un_id,
i.head_of_hh,
i.ind_first_name_ar,
i.ind_last_name_ar,
i.ind_first_name_en,
i.ind_last_name_en,
i.ind_gender,
i.dob,
i.ind_status
FROM individual i
WHERE i.household_id = :hid),
'HH Status Changed to inactive',
(SELECT i.ind_date_added,
i.user_id
FROM individual i
WHERE i.household_id = :hid),
:systemDate)
As you can see from the query, I am splitting the SELECT statement into 2 parts, as I want to insert a specific ind_action message, then I will continue by getting the other 2 fields date added and user_id.
The systemDate is the just the now() function result.
I tried to run this query using 12 as hid and I received the following error:
1136 - Column count doesn't match value count at row 1
After doing few searches, I found that I should add parenthesis for each of the values. So I changed the query to:
INSERT INTO individual_history
(individual_id,
household_id,
family_relation_id_history,
marital_status_id_history,
ind_lmms_id_history,
ind_un_id_history,
head_of_hh_history,
ind_first_name_ar_history,
ind_last_name_ar_history,
ind_first_name_en_history,
ind_last_name_en_history,
ind_gender_history,
dob_history,
ind_status_history,
ind_action,
ind_date_changed,
user_id,
system_date)
VALUES ((SELECT i.individual_id,
i.household_id,
i.family_relation_id,
i.marital_status_id,
i.ind_lmms_id,
i.ind_un_id,
i.head_of_hh,
i.ind_first_name_ar,
i.ind_last_name_ar,
i.ind_first_name_en,
i.ind_last_name_en,
i.ind_gender,
i.dob,
i.ind_status
FROM individual i
WHERE i.household_id = 12),
( 'HH Status Changed to inactive' ),
(SELECT i.ind_date_added,
i.user_id
FROM individual i
WHERE i.household_id = 12),
( NOW() ))
But still got the same error.
I tried to count the number of fields I am inserting compared to the ones I am selecting, and they are the same (18 fields).
UPDATE
I changed the query by removing the VALUES clause:
INSERT INTO individual_history
(
individual_id,
household_id,
family_relation_id_history,
marital_status_id_history,
ind_lmms_id_history,
ind_un_id_history,
head_of_hh_history,
ind_first_name_ar_history,
ind_last_name_ar_history,
ind_first_name_en_history,
ind_last_name_en_history,
ind_gender_history,
dob_history,
ind_status_history,
ind_action,
ind_date_changed,
user_id,
system_date
)
SELECT i.individual_id,
i.household_id,
i.family_relation_id,
i.marital_status_id,
i.ind_lmms_id,
i.ind_un_id,
i.head_of_hh,
i.ind_first_name_ar,
i.ind_last_name_ar,
i.ind_first_name_en,
i.ind_last_name_en,
i.ind_gender,
i.dob,
i.ind_status
FROM individual i
WHERE i.household_id=12,
'HH Status Changed to inactive',
(
SELECT i.ind_date_added,
i.user_id
FROM individual i
WHERE i.household_id=12),
now()
And I got the following error:
1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use
near '
'HH Status Changed to inactive',
' at line 10
Please note that the datatype of fields are exactly the same in both tables, and individual_history table contain an auto-increment primary key.
HERE IS AN SQL FIDDLE to check with sample data.
You don't need two SELECTs for what you're trying to do. If you want to use some specific value for ind_action, simply replace it in your select, same as you did with the now() function:
INSERT INTO targetTable (col1, col2, col3, col4, colTime)
SELECT colA, colB, 'my specific string', colD, now()
FROM sourceTable WHERE colA = 12;
Here, col3 gets the string, colTime the now().
#Marting Hennings, I am a bit too late ... but this query should work:
INSERT INTO individual_history
(individual_id,
household_id,
family_relation_id_history,
marital_status_id_history,
ind_lmms_id_history,
ind_un_id_history,
head_of_hh_history,
ind_first_name_ar_history,
ind_last_name_ar_history,
ind_first_name_en_history,
ind_last_name_en_history,
ind_gender_history,
dob_history,
ind_status_history,
ind_action,
ind_date_changed,
user_id,
system_date)
SELECT individual_id,
household_id,
family_relation_id,
marital_status_id,
ind_lmms_id,
ind_un_id,
head_of_hh,
ind_first_name_ar,
ind_last_name_ar,
ind_first_name_en,
ind_last_name_en,
ind_gender,
dob,
ind_status,
'HH Status Changed to inactive',
ind_date_added,
user_id,
now()
FROM individual
WHERE individual.household_id = 12

Get Field Based on FK

I didn't quite know how to word my issue, so I apologize for the odd title. I currently have two MySQL tables, business and users that look like the following respectively:
+-------------+----------+
| business_id | owner_id |
| 1 | 1 |
| 2 | 3 |
+-------------+----------+
+---------+-------------+----------------+
| user_id | business_id | email |
| 1 | 1 | a#domain.com |
| 2 | 1 | b#domain.com |
| 3 | 2 | c#domain.com |
+---------+-------------+----------------+
Right now, I need to get the email of the user where the business_id field in the user table matches that of the owner_id in the business table and I will always have the user_id (but it might not necessarily be the owner). To demonstrate what I mean, I can achieve what I want through this mess of a code:
SELECT
`email`
FROM
`user`
WHERE
`user_id` =(
SELECT
`owner_id`
FROM
`business`
WHERE
`business_id` =(
SELECT
`business_id`
FROM
`user`
WHERE
`user_id` = :user_id
)
)
So if I were to pass the a value of 1 or 2 for the user_id parameter, it would return a#domain.com and if I passed a value of 3 it would return c#domain.com.
I just feel as thought there is a better way!
Insead of subqueries you can use joins to achieve the same result by joining the user table twice with different aliases:
select u2.email
from user u1
inner join business b on u1.business_id=b.business_id
inner join user u2 on b.owner_id=u2.user_id
where u1.user_id=...
DEMO

MySQL Inner Join with No Rows

I have a MySQL database that I normalized and the idea is to allow for a business to select zero or more marketing sequences, but the kicker is that a handful of marketing sequences are required (right now I have 4, but the list can grow). So what I've done is structured my tables as such:
sequence
+-------------+------------------+-------+-------------+----------+
| sequence_id | customer_type_id | title | description | required |
| 1 | 1 | ... | ... | true |
| 2 | 1 | ... | ... | true |
| 3 | 1 | ... | ... | false |
| 4 | 2 | ... | ... | true |
| 5 | 3 | ... | ... | true |
| 6 | 4 | ... | ... | false |
+-------------+------------------+-------+-------------+----------+
business_sequence
+----------------------+-------------+-------------+
| business_sequence_id | business_id | sequence_id |
+----------------------+-------------+-------------+
customer_type_id and business_id are foreign key fields that link to tables that describe the type of customer (customer, former customer, etc.) and the business's information (name, address, etc.) respectively.
The reason why I have the required column in my sequence table is so that if a business decides not to allow for any of the non-required sequences, then that business would not need a row. After all, there's no need to have duplicate rows in the business_sequence table if the only piece of data that is different is the business_id field.
Now what I'm trying to do is get all the rows and all the fields from the sequence table where the business_id in the business_sequence table matches a parameterized value (say 1 for the example that I'm going to show in a second). The query that I tried to use is:
SELECT
s.*
FROM
`sequence` AS s
INNER JOIN `business_sequence` AS b ON b.`sequence_id` = s.`sequence_id`
WHERE
b.`business_id` = 1 AND
s.`required` = true;
But this returned no results if the business had no rows in the sequence table. What I expected it to do is return the 0 rows from the b.business_id = 1 but I also expected it to return the 4 "required" rows (ids: 1, 2, 4, and 5) from the s.required = true.
Whenever I took out the INNER JOIN statement and the business_id portion of the WHERE clause, it does in fact return the 4 "required" rows. This leads me to believe that in my original query, because there are no rows for that particular business_id in the sequence table it isn't returning anything.
With all of this being said, how do I accomplish retrieving the zero or more rows when the business_id field matches the parameterized value and retrieve all of the rows when the required field is true?
How about using OR condition in stead of AND ?
SELECT
s.*
FROM
`sequence` AS s
INNER JOIN `business_sequence` AS b ON b.`sequence_id` = s.`sequence_id`
WHERE
b.`business_id` = 1 OR
s.`required` = true;
I was able to resolve my problem by performing a UNION as such:
SELECT * FROM `sequence` WHERE `required` = true
UNION
SELECT
s.*
FROM
`sequence` AS s
INNER JOIN `business_sequence` AS b ON b.`sequence_id` = s.`sequence_id`
WHERE
b.`business_id` = 1

SQL Use Result from one Query for another Query

This is an excerpt from one table:
| id | type | other_id | def_id | ref_def_id|
| 1 | int | NULL | 5 | NULL |
| 2 | string | NULL | 5 | NULL |
| 3 | int | NULL | 5 | NULL |
| 20 | ref | 3 | NULL | 5 |
| 21 | ref | 4 | NULL | 5 |
| 22 | ref | 5 | NULL | 5 |
What I want is to find entries with type ref. Then I would for example have this one entry in my result:
| 22 | ref | 5 | NULL | 5 |
The problem I am facing is that I now want to combine this entry with other entries of the same table where def_id = 5.
So I would get all entries with def_id = 5 for this specific ref type as result. I somehow need the output from my first query, check what the ref_def_id is and then make another query for this id.
I really have problems to understand how to proceed. Any input is much appreciated.
If I understand correctly you need to find rows with a type of 'ref' and then use the values in their ref_def_id columns to get the rows with the same values in def_id. In that case you need to use a subquery for getting the rows with 'ref' type and combine it using either IN or EXISTS:
select *
from YourTable
where def_id in (select ref_def_id from YourTable where type='ref');
select *
from YourTable
where exists (select * from YourTable yt
where yt.ref_def_id=YourTable.def_id and yt.type='ref')
Both queries are equivalent, IN is easier to understand at first sight but EXISTS allow more complex conditions (for example you can use more than one column for combining with the subquery).
Edit: since you comment that you need also the id from the 'ref' rows then you need to use a subquery:
select source_id, YourTable.*
from YourTable
join (select id as source_id, ref_def_id
from YourTable
where type='ref')
as refs on refs.ref_def_id=YourTable.def_id
order by source_id, id;
With this for each 'ref' row you would get all the rows with the associated ref_id.
use below query to get column from sub query.
select a.ref_def_id
from (select ref_def_id from YourTable where type='ref') as a;
What you are looking for is a subquery or even better a join operation.
Have a look here: http://www.mysqltutorial.org/mysql-left-join.aspx
Joins / the left join allows you to combine rows of tables within one query on a given condition. The condition could be id = 5 for your purpose.
You would seem to want aggregation:
select max(id) as id, type, max(other_id) as other_id,
max(def_id) as def_id, ref_def_id
from t
where type = 'ref'
group by type, ref_def_id

mysql insert external data with join

I'm usually pretty resourceful, but I'm stuck on this one. Any help would be appreciated.
Say I've got a table for produce, like this, including counts of sold/in stock for each produce type.
+--------------+--------------+------+-----+
| Field | Type | Null | Key |
+--------------+--------------+------+-----+
| produce_type | varchar(100) | NO | PRI |
| sold_count | int(8) | YES | |
| stock_count | int(8) | YES | |
+--------------+--------------+------+-----+
I'm doing a separate insert using external data for each of the 'stock' and 'sold' counts, with hundreds to thousands of produce_types at a time. I may have data with a given produce_type existing only in the 'stock' or 'sold' data to be inserted, but want all to be present in the table.
So, e.g., doing one insert for sold_count ('potato', 3), ('onion', 5) and one for stock_count ('potato', 8), ('carrots', 6), I'd want to end up with this:
+--------------+------------+-------------+
| produce_type | sold_count | stock_count |
+--------------+------------+-------------+
| potato | 3 | 8 |
| onion | 5 | NULL |
| carrots | NULL | 6 |
+--------------+------------+-------------+
So I'd need to join to existing data upon the second column's insert statement, but all I see here or elsewhere on the web is instructions for joins when inserting from another table.
INSERT IGNORE doesn't do it, as one of the 'potato' columns wouldn't get written to.
INSERT ... ON DUPLICATE KEY UPDATE gets closer but I can't figure out how to set the update field to the value from the dataset I'm inserting.
Do I need to create a temp table for the 2nd insert (+ outer join)? Any structurally simpler way of doing this?
Thanks in advance.
Edit: I think I can probaly use this:
https://stackoverflow.com/a/3466/2540707
Does this work?
insert into produce ( produce_type, sold_count )
select produce_type, sold_count from sold_data
on duplicate key update sold_count = ( select sold_count from sold_data
where produce.produce_type = sold_data.produce_type
);