Union tables into 1 with a flag indicating the respective table entries - mysql

i have 2 tables.
1.home_shop
+---+------------+
|id | product |
+---+------------+
| 1 | soap |
| 2 | cake |
| 3 | biscuit |
+---+------------+
2.office_shop
+---+------------+
|id | product |
+---+------------+
| 1 | key |
| 2 | lock |
| 3 | pen |
+---+------------+
what i want is union this two tables into a new table "complete_shop" with a flag indicating "home" and "office"
for example:
+---+------------+-------------+
|id | product | flag |
+---+------------+-------------+
| 1 | soap | home |
| 1 | key | office |
| 2 | cake | home |
| 2 | lock | office |
| 3 | biscuit | home |
| 3 | pen | office |
+---+------------+-------------+
how do i do this union in mysql please help me. i am a beginner

Do a UNION query and introduce the flag column using the appropriate values.
SELECT id, product, 'home' AS flag
FROM home_shop
UNION ALL
SELECT id, product, 'office' AS flag
FROM office_shop
ORDER BY id, flag
Note that you don't need to use a subquery to order here, you can just specify the columns you want to use.

Related

Does Cross Join not work between two different tables with same column name?

As written on the title, does CROSS JOIN not work for different tables with the same column name?
For example,
I have one table named Fruits:
| name | price |
| apple | 1 |
| banana | 2 |
and another table named Snacks:
| name | price |
| chips | 3 |
| cookies | 4 |
Then does
SELECT Fruits.price, Snacks.price FROM Fruits CROSS JOIN Snacks
does not work properly?
I am working on a same issue, but the result shows like:
| price | price |
| 3 | 3 |
| 4 | 4 |
| 3 | 3 |
| 4 | 4 |
But what I expect is:
| price | price |
| 1 | 3 |
| 1 | 4 |
| 2 | 3 |
| 2 | 4 |
As I mentioned in the comment, it is not possible. Either your tables values are different or your query.
Check this dbfiddle showing the result value same as your expected values.
In MySQL CROSS JOIN works as expected:
price price
------ -----
1 3
2 3
1 4
2 4
See running example at DB Fiddle.

Left joins, i need an explanation about a code

i am watching a tutorial. There is a code which i don't understand what is supposed to do.
$sql = 'SELECT p.*,
a.screen_name AS author_name,
c.name AS category_name
FROM
posts p
LEFT JOIN
admin_users a ON p.author_id = a.id
LEFT JOIN
categories c ON p.category_id = c.id
WHERE
p.id = ?';
I read about the left joins but i didn't understand them. Can somebody please explain me the code i shared.
Thanks in advance!
Imagine you have two tables. One that stores the information about the programmers on your website, and the other table that keeps track of their online purchases.
PROGRAMMERS Table
+--------------------------------------------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Desire | 32 | 123 fake s| 3000.00 |
| 2 | Jamin | 25 | 234 fake s| 2500.00 |
| 3 | Jon | 23 | 567 fake s| 2000.00 |
| 4 | Bob | 30 | 789 fake s| 1500.00 |
| 5 | OtherGuy | 31 | 890 fake s| 1000.00 |
| 6 | DudeMan | 32 | 901 fake s| 500.00 |
+--------------------------------------------+
PURCHASES Table
+---------------------------------------------+
| ORDER_ID | PROG_ID | DATE | PRICE |
+-------------+---------+---------------------|
| 1 | 1 | 1-1-2017 | 100 |
| 2 | 2 | 1-2-2017 | 200 |
| 3 | 6 | 1-3-2017 | 300 |
+---------------------------------------------|
You decide you need to make a new table to consolidate this information to a table that contains
certain columns you want.
For example, you figure it would be nice for shipping purposes to have a table
that has the ID, the NAME, the PRICE, and the DATE columns.
Currently, the tables we have don't display all of that in a single table.
If we were to LEFT JOIN these tables, we would end up filling the desired columns
with NULL values where there is no information to join.
SELECT ID, NAME, PRICE, DATE
FROM PROGRAMMERS
LEFT JOIN PURCHASES
ON PROGRAMMERS.ID = PURCHASES.PROG_ID;
Notice that I'm selecting the columns I want from the starting table, then joining the right table
even though there might be missing information.
RESULTING TABLE
+-------------------------------------+
| ID | NAME | PRICE | DATE |
+----+----------+-----------------+---+
| 1 | Desire | 100 | 1-1-2017 |
| 2 | Jamin | 200 | 1-2-2017 |
| 3 | Jon | NULL | NULL |
| 4 | Bob | NULL | NULL |
| 5 | OtherGuy | NULL | NULL |
| 6 | DudeMan | 300 | 1-3-2017 |
+-------------------------------------+
For a visual representation of the difference between SQL JOINs check out
https://www.codeproject.com/Articles/33052/Visual-Representation-of-SQL-Joins .

MySQL combining outer joins

For this question I have created a simple example that illustrates what I am asking.
Say I had a table called 'books'
+----+----------------------------+-----------+
| pk | title | author_id |
+----+----------------------------+-----------+
| 1 | The Lost Symbol | 1 |
| 2 | Follow Us Home | 2 |
| 3 | The Man in the High Castle | 3 |
+----+----------------------------+-----------+
(table a)
And another table called 'shops', that had a list of shops that sold each book:
+----+---------+-------------+-------+
| pk | book_id | shop_name | price |
+----+---------+-------------+-------+
| 1 | 1 | WHSmith | 5.00 |
| 2 | 1 | Waterstones | 7.00 |
| 3 | 1 | Amazon | 2.50 |
| 4 | 2 | WHSmith | 4.00 |
| 5 | 2 | Borders | 4.50 |
+----+---------+-------------+-------+
(table b)
If I do a simple select that grabs a book and all of the places it is sold using a join such as:
SELECT
books.*,
shops.shop_name,
shops.price
FROM
books
JOIN shops ON books.pk = shops.book_id
WHERE
book.book_name = "The Lost Symbol"
I would get results such as below:
+----+-----------------+-----------+-------------+-------+
| pk | title | author_id | shop_name | price |
+----+-----------------+-----------+-------------+-------+
| 1 | The Lost Symbol | 1 | WHSmith | 5.00 |
| 1 | The Lost Symbol | 1 | Waterstones | 7.00 |
| 1 | The Lost Symbol | 1 | Amazon | 2.50 |
+----+-----------------+-----------+-------------+-------+
(table c)
However, I would LIKE to receive results like this:
+----+-----------------+-----------+-------------+-------+
| pk | title | author_id | shop_name | price |
+----+-----------------+-----------+-------------+-------+
| 1 | The Lost Symbol | 1 | NULL | NULL |
| 1 | The Lost Symbol | 1 | WHSmith | 5.00 |
| 1 | The Lost Symbol | 1 | Waterstones | 7.00 |
| 1 | The Lost Symbol | 1 | Amazon | 2.50 |
+----+-----------------+-----------+-------------+-------+
(table d)
I.e. the first row is just the result of left outer join and the rest of the results are the the inner join.
An even more desired outcome is:
+------+-----------------+-----------+-------------+-------+
| pk | title | author_id | shop_name | price |
+------+-----------------+-----------+-------------+-------+
| 1 | The Lost Symbol | 1 | NULL | NULL |
| NULL | NULL | NULL | WHSmith | 5.00 |
| NULL | NULL | NULL | Waterstones | 7.00 |
| NULL | NULL | NULL | Amazon | 2.50 |
+------+-----------------+-----------+-------------+-------+
(table e)
Having shop_name and price concatenated and grouped in a single row seems not to work as it only does the first result from shops instead of all of them, also in my real world scenario, I have punctuation in the data so have to be careful with the separator.
So how would I get the result of table e?
You can use UNION ALL to build the required result set:
SELECT pk, title, author_id, NULL AS shop_name, NULL AS price
FROM books
WHERE books.title = "The Lost Symbol"
UNION ALL
SELECT NULL AS pk, NULL AS title, NULL AS author_id, shops.shop_name, shops.price
FROM books
JOIN shops ON books.pk = shops.book_id
WHERE books.title = "The Lost Symbol"
The first part of the union operation returns the first row of the result, i.e. the book title. The second part returns the rest of the rows, i.e.the shop names.
Demo here

How select remaining unspecified columns

I am looking to overwrite a column name in a table with an existing column name.
I am Looking for a way to get the remaining unspecified columns in the tables.
Note:
The query could have more joins in the future.
eg
Person
+-----------+----------+---------+
| firstname | lastname | pers_id |
+-----------+----------+---------+
| Joe | Soap | 1 |
| Bobby | Pin | 2 |
| Janet | Jackson | 3 |
+-----------+----------+---------+
Category
+----------+-------------------+--------+
| type | description | cat_id |
+----------+-------------------+--------+
| customer | people who pay us | 1 |
| employee | people we pay | 2 |
| director | people who direct | 3 |
+----------+-------------------+--------+
Person_Cat
(=^ェ^=)
+---------+--------+
| pers_id | cat_id |
+---------+--------+
| 3 | 1 |
| 2 | 2 |
| 1 | 3 |
+---------+--------+
Query
SELECT *, CONCAT(p.firstname, ' '
, p.lastname) as full_name
, c.cat_id AS category_id
, p.pers_id AS cat_id
FROM Person AS p
JOIN Person_Cat AS pc ON(p.pers_id = pc.pers_id)
JOIN Category AS c ON (pc.cat_id = c.cat_id)
OUTPUT
(Apologies for the length but the table after is more important)
+-----------+----------+---------+---------+--------+----------+-------------------+--------+---------------+-------------+--------+
| p | p | p | pc | pc | c | c | c | Select | Select | Select |
+-----------+----------+---------+---------+--------+----------+-------------------+--------+---------------+-------------+--------+
| firstname | lastname | pers_id | pers_id | cat_id | type | description | cat_id | full_name | category_id | cat_id |
+-----------+----------+---------+---------+--------+----------+-------------------+--------+---------------+-------------+--------+
| Janet | Jackson | 3 | 3 | 1 | customer | people who pay us | 1 | Janet jackson | 1 | 3 |
| Bobby | Pin | 2 | 2 | 2 | employee | people who we pay | 2 | Bobby Pin | 2 | 2 |
| Joe | Soap | 1 | 1 | 3 | director | people who direct | 3 | Joe Soap | 3 | 1 |
+-----------+----------+---------+---------+--------+----------+-------------------+--------+---------------+-------------+--------+
The headers above column names are there for reference
to where they comes from.
Column summary -
firstname, lastname, pers_id, pers_id, cat_id, type,
description, cat_id, full_name ,category_id, cat_id
Wanted output
+-----------+----------+---------+--------+----------+-------------------+---------------+-------------+--------+
| p | p | pc | pc | c | c | Select | Select | Select |
+-----------+----------+---------+--------+----------+-------------------+---------------+-------------+--------+
| firstname | lastname | pers_id | cat_id | type | description | full_name | category_id | cat_id |
+-----------+----------+---------+--------+----------+-------------------+---------------+-------------+--------+
| Janet | Jackson | 3 | 1 | customer | people who pay us | Janet jackson | 1 | 3 |
| Bobby | Pin | 2 | 2 | employee | people who we pay | Bobby Pin | 2 | 2 |
| Joe | Soap | 1 | 3 | director | people who direct | Joe Soap | 3 | 1 |
+-----------+----------+---------+--------+----------+-------------------+---------------+-------------+--------+
Column summary -
firstname, lastname, pers_id, cat_id, type,
description, full_name ,category_id, cat_id
Notice:
The p.pers_id and the c.cat_id are not present. I would like to think this would be because the were called directly and unmodified unlike the first and lastname used in ConCat
When the short answer is that there is no such concept as Select [remaining columns]at this time (2015-06-17), if you want to use SELECT * but only remove redundant columns,
then you will need to explicitly remove (ignore) those redundant columns when rendering your view.
You will have to explicitly configure logic of which columns to ignore, which is pretty much the same thing as explicitly listing the columns that you are interested in, so you get back to the argument against selecting all columns that I made in the comments above.
Unless your table schema is changing all the time, there really isn't reason for this.

build dynamic sql insert query to merge multiple tables into single table using mapping table

I am looking to take data from multiple mysql tables with different structures and insert it into one master table containing different columns/data from the sources,
I have created a column name mapping table with the following data:
TABLE: affiliate_datafeed_magento_mapping
+----+-------------+----------------+
| id | datafeed | magento |
+----+-------------+----------------+
| 1 | SKU | sku |
| 1 | Name | name |
| 1 | Description | description |
| 1 | Url | affiliate_link |
| 1 | Price | price |
| 1 | Brand | brand |
| 1 | ModelNumber | model |
| 2 | SKU | sku |
| 2 | Name | name |
| 2 | Description | description |
| 2 | Url | affiliate_link |
| 2 | Price | price |
| 2 | Currency | affiliate_cur |
+----+-------------+----------------+
id corresponds to the id of the affiliate program in the table affiliate_programs
datafeed corresponds the column name in the source table with the corresponding id in the table affiliate_program
magento corresponds the the column name in the table to receive the data
TABLE: affiliate_programs
+----+-------------------+-------------------------+------------------------+------------------------+-------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-----------------------------------------+-------------------------------------+-------+
| id | affiliate_network | affiliate_network_short | affiliate_program | affiliate_program_long | affiliate_program_short | affiliate_program_datafeed_url | affiliate_program_datafeed_csv_filename | affiliate_program_datafeed_last_get | order |
+----+-------------------+-------------------------+------------------------+------------------------+-------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-----------------------------------------+-------------------------------------+-------+
| 1 | CommissionFactory | cf_ | Lifestyle Clotheslines | lifestyleclotheslines | lcl | http://dashboard.commissionfactory.com.au/Affiliate/Creatives/DataFeeds/jPuB5NPigbec7prnjLCX5MHygO$A5sTlhOHb8t3nmufzta#k5uyn5qqxrLDr86GysLTj$bTyoKaj77Pltfmh9dvnkOCS4MHzjvTSlK6Dfg==/ | cf_lifestyleclotheslines.csv | 2013-08-12 22:23:02 | NULL |
| 2 | CommissionFactory | cf_ | MacArthur Baskets | macarthurbaskets | mcb | http://dashboard.commissionfactory.com.au/Affiliate/Creatives/DataFeeds/jPSA4dbg17SY7svvjeSX5Jf1iO#b5JXshOfY#ovjzeKj4PGivuyn5qqxrLDr86GysLTj$bTyoKaj77Pltfmh9dvnkOCS4MHzjvTSlK6Dfg==/ | cf_macarthurbaskets.csv | 2013-08-12 22:23:02 | NULL |
| 3 | ClixGalore | cg_ | Boutique Wineries | boutiquewineries | btw | http://www.is1.clixGalore.com/DataFileRequest.aspx?AdID=9522&AfID=264058 | cg_boutiquewineries.csv | 2013-08-12 22:23:02 | NULL |
| 4 | ClixGalore | cg_ | Brewtopia | brewtopia | bwt | http://www.is1.clixGalore.com/DataFileRequest.aspx?AdID=4817&AfID=264058 | cg_brewtopia.csv | 2013-08-12 22:23:02 | NULL |
| 5 | ClixGalore | cg_ | MacArthur Baskets | macarthurbaskets | mcb2 | http://www.is1.clixGalore.com/DataFileRequest.aspx?AdID=4909&AfID=264058 | cg_macarthurbaskets.csv | 2013-08-12 22:23:02 | NULL |
| 6 | ClixGalore | cg_ | Winemakers Choice | winemakerschoice | wmc | http://www.is1.clixGalore.com/DataFileRequest.aspx?AdID=4282&AfID=264058 | cg_winemakerschoice.csv | 2013-08-12 22:23:02 | NULL |
+----+-------------------+-------------------------+------------------------+------------------------+-------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-----------------------------------------+-------------------------------------+-------+
id corresponds to the same id in the table affiliate_datafeed_magento_mapping
the concatenation of affiliate_programs.affiliate_network_short and affiliate_programs.affiliate_program_long make up the name of the source table
TABLE: cf_lifestyleclotheslines
+----+---------------------+---------------------+------+------------------------------------------------------+--------------------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------+---------------------------------------------------------------------------------------------------+-------------------------------------------------------------------+-------------------------------------------------------------------------+---------------------------------------------------------------------------+---------------------------------------------------------------------------+---------------------------------------------------------------------------+---------------------------------------------------------------------------+---------------------------------------------------------------------------+--------------+-------------+-------------+
| id | DateCreated | DateModified | SKU | Name | Category | Description | Url | OriginalUrl | Image | Image50 | Image100 | Image120 | Image200 | Image300 | Image400 | Price | Brand | ModelNumber |
+----+---------------------+---------------------+------+------------------------------------------------------+--------------------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------+---------------------------------------------------------------------------------------------------+-------------------------------------------------------------------+-------------------------------------------------------------------------+---------------------------------------------------------------------------+---------------------------------------------------------------------------+---------------------------------------------------------------------------+---------------------------------------------------------------------------+---------------------------------------------------------------------------+--------------+-------------+-------------+
| 1 | 2012-10-19 10:52:50 | 2013-06-20 02:07:37 | 30 | Airaus Ceiling Mounted Clothes Airer | Home & Garden > Household Supplies > Laundry Supplies > Drying Racks & Hangers | Watch the Product Video Just arrived from Europe! Lifestyle Clotheslines is now stocking the latest ceiling mounted clothes airers from Europe. Ceiling mounted clothes airers are the perfect alternative for those with limited space situations or who need the benefit of an indoor clothesline or airer. Boasting 6 individually adjustable drying rods which are made of steel not plastic, these indoor airers can be used in a range of situations and are ideally suited for the disabled as they can easily be lowered or raised to the height of the user. An indoor airer can also help extend the life of your clothes by reducing the exposure to harsh UV rays and they can also be a big power saver for your home when used to dry your washing instead of a tumble dryer. Discover today how one of our new ceiling mounted clothes airers can save you money and take all the hard work and fuss out of drying your washing. // Customer Video Reviews &nbsp... | https://track.commissionfactory.com.au/p/10604/1718691 | http://www.lifestyleclotheslines.com.au/airaus-ceiling-mounted-clothes-airer/ | http://content.commissionfactory.com.au/Products/7228/1718691.jpg | http://content.commissionfactory.com.au/Products/7228/1718691#50x50.jpg | http://content.commissionfactory.com.au/Products/7228/1718691#100x100.jpg | http://content.commissionfactory.com.au/Products/7228/1718691#120x120.jpg | http://content.commissionfactory.com.au/Products/7228/1718691#200x200.jpg | http://content.commissionfactory.com.au/Products/7228/1718691#300x300.jpg | http://content.commissionfactory.com.au/Products/7228/1718691#400x400.jpg | 99.0000 AUD | | AIRAUS |
+----+---------------------+---------------------+------+------------------------------------------------------+--------------------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------+---------------------------------------------------------------------------------------------------+-------------------------------------------------------------------+-------------------------------------------------------------------------+---------------------------------------------------------------------------+---------------------------------------------------------------------------+---------------------------------------------------------------------------+---------------------------------------------------------------------------+---------------------------------------------------------------------------+--------------+-------------+-------------+
So with the data provided I'm looking to go through all the tables (concatenation of affiliate_programs.affiliate_network_short and affiliate_programs.affiliate_program_long columns in affiliate_programs and build a insert query for them all based on the mapped columns in the table affiliate_datafeed_magento_mapping to insert the data into the table magento_export
Any assistance would be awesome!
Tim
I dont think you need the mapping table at all
I would use a series of UNION queries. One query per source. In the SELECT clause for each of those queries you should have a 1:1 column for each coulmn in your destination table, including mapping the value NULL where that destination column is not applicable to that source. (This is where the mapping really happens)
Then your INSERT statement is a straight-forward mapping of all the UNIONED queries into the destination table.
Pseudo code
INSERT INTO Destination(Col1, Col2, Col3, Col4)
SELECT T1.Field1 as Col1
,NULL as Col2
,T1.Field7 as Col3
,T1.Field2 as Col4
FROM FirstSource T1
UNION
SELECT T2.Field1 as Col1
,Some Calulation as Col2
,T2.Field3 as Col3
,NULL as Col4
FROM FirstSource T1