How to avoid duplicate columns when doing left join? - mysql

I have two tables. Each has number of columns. But both has two columns in common.(ie: SiteCode,companyId)
I try to do left join for both common columns to create a view.
CREATE VIEW [dbo].[vwAlarmActionSummaryYFUserSite]
AS
SELECT *
FROM [dbo].[vwAlarmActionSummary] alarmaction
LEFT JOIN [dbo].[vwYfUserToSiteMappings] usersite on alarmaction.SiteCode = usersite.SiteCode
and alarmaction.CompanyId = usersite.CompanyId
But Im getting
Column names in each view or function must be unique. Column name 'SiteCode'on 'vwAlarmActionSummaryYFUserSite' is specified more than once.
How can I avoid this?
My requirement is get all columns from those two tables based on the above two conditions

It is very bad practice to use * in definitions view generally. There is no way to specifically exclude a column from one of the joined tables. However, you can use * (all columns) for one table, while providing explicit column names for the other, as below:
CREATE VIEW [dbo].[vwAlarmActionSummaryYFUserSite]
AS
SELECT
alarmaction.[column name],
...
usersite.*
FROM [dbo].[vwAlarmActionSummary] alarmaction
LEFT JOIN [dbo].[vwYfUserToSiteMappings] usersite on
alarmaction.SiteCode = usersite.SiteCode
and alarmaction.CompanyId = usersite.CompanyId
Best practice is still to explicitly list all columns from both tables, and include 'SiteCode' only once.

Don't select *. Pick your column names.

Related

Join only subset of columns with sqlalchemy core

Is there a clean way to join two tables but only select a subset of the joined table's columns?
e.g.
join_query = table_a.join(table_b, columns=[table_b.c.column_a, table_b.c.column_b])
I'm trying to avoid using select since I would have to list dozens of needed columns from table_a, but I want only a couple columns from column b.
Stumbled upon the way to do it, select can take either specific columns or full table references as args, so the answer would be
join_query = table_a.join(table_b).select(table_a, table_b.c.column_a, table_b.column_b)

SQL: How do add a prefix to column names in a JOIN?

I have sql query like this
SELECT * FROM phlegm WHERE JOIN mucus ON phlegm.id = mucus.id JOIN snot ON phlegm.id = snot.id
The problem is those tables contain several columns with identical names.
For example all 3 tables contain the column named test
If I retrieve the result of the query in PHP, then I will only get one value named test ($query->get_result()->fetch_object()->test;), because the other two get overwritten.
Is there some way to edit that query so that it adds a prefix to all columns from a table? For example, column test from table mucus would be referenced in the query as mucus_test and column test from phlegm would be phlegm_test.
One way would be doing
SELECT phlegm.test as phlegm_test, mucus.test as mucus_test FROM phlegm...
But I have a LOT of columns and tables and it would make the query longer than the Great Wall of China if I had to name each field one by one.
So is there some way to add the prefix en masse?
SELECT *, phlegm.test as phlegm_test, mucus.test as mucus_test FROM phlegm...
Used aliasing to retrieve all values associated from all three tables. if you want to reference only specific column do so by using the alias_name.column_name instead of p.*, where * means all columns belonging to table that the alias is associated with( ie. p refers to phlegm).
SELECT p.*, m.*, s.*
FROM phlegm p
JOIN mucus m ON p.id = m.id
JOIN snot s ON p.id = s.id;
I removed the WHERE from your original query above, not sure why it was there.

Mysql: Select all columns and add alias with original column name

I have 2 tables connected via join. Both tables share some column names. I need to distinguish between those columns. So I am looking for something like this:
SELECT t1.* AS t1_* , t2.* AS t2_*
FROM t1
LEFT JOIN t2
ON t1.id=t2.somefield
Meaning if in both table is a column "place", the column names should appear in the result list as "t1_place" and "t2_place".
I did not find if this would be possible somehow. The reason is that both tables are rather large so I try to avoid listing all the columns and assigning aliases.
Any suggestions?

Joining 5 tables - 1 master plus 4 with multiple rows to the master but master data is duplicated

I am working in mysql with queries, but I am new to this. I am joining 5 tables where each table has an identifier and one table is the master. Each related table may have more than one associated record to the master table. I am attempting to join these tables but I can't seem to get rid of the duplicated data.
I want all of the related records to be displayed, but I don't want the data in the master table to display for all results in the related tables. I have tried so many different methods but nothing has worked. Currently I have 4 queries that work for the separate tables, but I have not successfully joined them to have the results display the multiple records in the related table but just one record from the master table.
Here are my individual queries that work:
SELECT
GovernmaxAdditionsExtract.AdditionDescr,
GovernmaxAdditionsExtract.BaseArea,
GovernmaxAdditionsExtract.Value
FROM
GovernmaxExtract
INNER JOIN GovernmaxAdditionsExtract
ON GovernmaxExtract.mpropertyNumber = GovernmaxAdditionsExtract.PropertyNumber
WHERE (((GovernmaxExtract.mpropertyNumber)="xxx-xxx-xx-xxx"));
SELECT
GovernmaxExtract.mpropertyNumber,
GovernmaxDwellingExtract.CardNumber,
GovernmaxDwellingExtract.MainBuildingType,
GovernmaxDwellingExtract.BaseArea
FROM
GovernmaxExtract INNER JOIN
GovernmaxDwellingExtract ON GovernmaxExtract.mpropertyNumber = GovernmaxDwellingExtract.PropertyNumber
WHERE (((GovernmaxExtract.mpropertyNumber)="xxx-xxx-xx-xxx"));
Using these sub queries, I tried to put together 2 of the tables, but now I am getting all records back and it is not reading my input parameter:
SELECT GE.mpropertynumber
FROM
GovernmaxExtract AS GE,
(SELECT
GovernmaxAdditionsExtract.AdditionDescr,
GovernmaxAdditionsExtract.BaseArea,
GovernmaxAdditionsExtract.Value
FROM GovernmaxExtract INNER JOIN
GovernmaxAdditionsExtract ON
governmaxextract.mpropertyNumber = GovernmaxAdditionsExtract.PropertyNumber) AS AE
WHERE GE.mpropertynumber = 'xxx-xxx-xx-xxx'
I tried nested queries, lots of different joins, and I am just not able to wrap my head around this. I am pretty sure I want to do a nested query since I want the main data from the Governmax table to display once with the main data and all records with all info for the associated tables. Maybe I am going about it all wrong.
Our original code was:
SELECT
ge.*,
gde.*,
gfe.*,
gae.*,
goie.*
FROM governmaxextract AS ge
LEFT JOIN governmaxdwellingextract AS gde
ON ge.mpropertyNumber = gde.PropertyNumber
LEFT JOIN governmaxfeaturesextract AS gfe
ON gde.PropertyNumber = gfe.PropertyNumber
LEFT JOIN governmaxadditionsextract AS gae
ON gde.PropertyNumber = gae.PropertyNumber
RIGHT JOIN governmaxotherimprovementsextract AS goie
ON gde.PropertyNumber = goie.PropertyNumber
WHERE ge.mpropertyNumber = '$codeword'
ORDER BY goie.CardNumber
But this gives multiple rows from the master table for each record in the associated tables. I thought about concatenate, but I need the data from the associated tables to be displayed individually. Not sure what to try next. Any help is much appreciated.
Sorry, and there is no way to do that like you want. JOIN's can't do that.
I suggest to keep solution with separate queries.
Btw - You could play with UNION operator,
http://en.wikipedia.org/wiki/Union_(SQL)#UNION_operator
P.s.
You could extract main data separately, then extract data from related tables at once using UNION. With UNIOM it will give one result row per each row in related table.
In order to join an two of the Detail tables together without generating duplicate rows, you will have to perform the following operation on each one:
Group on the foreign key to the Master table, and aggregate all other columns being projected onto the join.
Numeric columns are commonly aggregated with SUM(), COUNT(), MAX(), and MIN(). MAX() and MIN() are also applicable to character data. A PIVOT operation is also sometimes useful as an aggregation operator for this type of circumstance.
Once you have two of the Detail tables grouped and aggregated in this way, they will join without duplicates. Additional Detail tables can be added to the join by first grouping and aggregating them also, in the same fashion.

mysql getting difference of 2 result sets

So I have two tables. One is called superIDs which has columns "superID BIGINT" and I have another one called mainIDs which has a column called "subid BIGINT". I know that mainIDS is a subset of superIDs. How can I see the rows that are ONLY in superID but not in mainIDs.
here is my attempt at a solution:
SELECT * FROM atlas_comparables.superIDs WHERE NOT EXISTS
(SELECT * FROM atlas_comparables.mainIDs);
However, this is returning me an empty set. Any help?
Try this
SELECT * FROM atlas_comparables.superIDs WHERE the_id_column NOT IN
(SELECT the_idcolumn_ofcomparable FROM tlas_comparables.mainIDs);
Note: the_id_column is in superIDs table
the_idcolumn_ofcomparable is in MainIdstable
If the ids only appear (at most) once in each table, then you can do this relatively easily with a left outer join:
select si.*
from atlas_comparables.superIDs si left join
atlas_comparables.mainIDs mi
on si.SuperID = mi.SubID
where mi.SubId is NULL;
If you are trying to compare all the columns (as except does in other databases), then you need a more complicated query, where you include all the columns on the on clause.