MYSQL Selecting multiple values from the same column as a row - mysql

I have two tables
table COMMUNITY
id,
name,
etc.
table PROPERTY
id,
community_id,
type,
price,
rate,
etc.
There are four possible property types and a community can have info for one or more of the different types.
I am trying to figure out how to combine the information for each community into one row.
For instance I might want to get a row which includes
community.id, community.name, condo.price, condo.rate, town_home.price, town_home.rate
Of course there aren't tables for condo or town_home, the property type is represented in the property table by a column and a community can have multiple property rows.
My first thought was to use multiple joins on the table with aliases, but I can't seem to get anything that works properly.
Any suggestions?

You can use left join for this.
SELECT c.id, c.name, condo.price, condo.rate, town_home.price, town_home.rate
FROM Community c
LEFT JOIN Property condo ON condo.community_id = c.id AND condo.type = 'condo'
LEFT JOIN Property town_home ON town_home.community_id = c.id AND town_home.type = 'town_home'

I am the kind of person who doesn't like much to use joins, might be because I don't see much reason as for use them or as I wouldn't need it.
By any means, this is the way I would put it:
As you have a link between the two tables, you are able to use them to bring you the data you need, as long as you have this link you can bring whatever field you want.
So you said you wanted the fields:
community.id, community.name, condo.price, condo.rate, town_home.price, town_home.rate
SELECT
community.id,
community.name,
condo.price,
condo.rate
FROM
community, property condo
WHERE
community.id = condo.community_id;
This should solve it.

Try this:
SELECT * FROM community LEFT OUTER JOIN property ON community.id = property.community_id;
This should join the two tables on the ID field, so you should have one complete row with all of the information. if anything is null, it should be present in the row, as well. If multiple properties are listed with the same community ID, they should all come up in the result.
PS - I use PostgreSQL and not MYSQL so the syntax might be a bit different. Let me know how it works!

Related

Overlap of unique Identifiers when trying to pull/expand data

LoadTableQuery.Qry = #"
SELECT `orders`.`ordID`,
`orders`.`OrderType`,
`prt`.`Name`,
`orders`.`prtID`,
`orders`.`ReqRef`,
`orders`.`DateOrdered`,
`orders`.`orderETA`,
`orders`.`DateRcvd`,
`orders`.`Status`,
`orders`.`ShipCost`,
`orders`.`Duties`,
`orders`.`Currency`,
`orders`.`Conv`,
`orders`.`Terms`,
`orders`.`Shipping`,
`orders`.`BuyerID`,
`orders`.`ShipTo`,
`orders`.`Notes2`,
`orders`.`Notes3`,
`orders`.`legacyID`,
`prt`.`Address`,
`prt`.`City`,
`prt`.`StateProv`,
`prt`.`PostalZip`,
`prt`.`Tel`,
`prt`.`Contact`,
`prt`.`Email`,
`prt`.`OrderTaxPc`
FROM `n2000`.`orders` left join `n2000`.`prt`
on (orders.prtID = prt.prtID)
prtID is a unique identifier which I'm using to pull the data I need about the party (their name, address, city..). The way it's written above works, accomplishing what I need it to do. getting and inserting the data into my table.
The issue is, I need a SECOND set of party data, based on orders.ShipTo instead of orders.prtID . ShipTo is really just a different prtID.
I'd like to be able to just run it again with
on (orders.ShipTo = prt.prtID).
I've tried using UNION, but that creates a new row, instead of adding columns to my current row. Which is where I'm looking to pull my data from.
The best way to understand it is, I've expanded prtID to add the Name, Address, City.. column data. I'd like to expand ShipTo as well. I don't know how to do that though without simply overwriting the prtID expansion.
The solution was actually quite simple. Hope this helps someone else
Solution
The solution was actually quite simple. Alias the different tables and do a double left join
Solution

Pulling data from two tables (for a 'related products' query) in MySQL

I'm trying to pull data from two tables for a 'related products' widget.
I've tried all the JOINS and UNIONS I can and still get nothing.
The first table (productdocs) stores documents. The second (prodrelated) shows when a product is related to a document:
productdocs
pdid (unique ID for the document)
pdname (name of the uploaded document)
prodrelated
prprodid (the ID for the PRODUCT)
pritemid (the ID for the document)
I am trying to output the productdocs.pdname for any documents that match up with the product's id. In otherwords, show the pdname when:
WHERE productdocs.pdid = prodrelated.pritemid
I would post my SQL code, but none of it has worked, so I think it would be pointless. I hope I explained this correctly given my frazzled brain - Any help greatly appreciated.
You can use a simple INNER JOIN for this, e.g.:
SELECT pd.pdid, pd.pdname
FROM productdocs pd JOIN prodrelated pr ON pd.pdid = pr.pritemid
WHERE pd.prprodid = <any_id>;
If you don't want to filter out any records, you can get rid of WHERE clause and it will output all the records.
Here's MySQL's documentation for JOIN.
Wow you guys are fast - thank you so much.
Darshan - thank you above all, I was able to make a few mods to what you wrote and it worked great. I tried to +1 your answer but maybe I don't have enough 'reputation'? Here is what I got working, thanks to you:
SELECT pd.pdid, pd.pdname
FROM productdocs pd
JOIN prodrelated pr
ON pd.pdid = pr.pritemid
WHERE pr.prprodid = '#url.prodid#'
In the future I will try to post some code example, but on this one I honestly tried at least 7 different queries so I had no idea which to post!

SQL Is this Outer or Inner Join and how to join on Array

Seemed simple when I started and have done this before, now I confused myself and at a road block.
Have two tables: News_Table and a People_Table. Under the News_Table there is a field: News_People_Contributed and it has the ID's of the People_Table in array format (1,4,7,10) thus Four People contributed. I am creating a search parameter that looks up News_Header AND News_People_Contributed and can't figure how to create the search column.
News_Table
News_ID
News_Header
News_People_Contributed
People_Table
People_ID
People_First_Name...
Is it something like...
Select*
From News_Table
Left Join News_Table
On People_Table.People_ID IN (News_Table.News_People_Contributed)
Where Search_Param Like '%News_Header%' OR Search_Param Like '%People_First_Name%'
The problem is (News_Table.News_People_Contributed) is a string and the ID's are not. Plus I may not have people contributed etc. To make the issue even more complex, I'm doing this in MS Access instead of MySql, so have to code it "old school" sql for work around.
Perform a cross join and filter on matches in the string list. It says nothing about efficiency or form (as already commented on), but it works.
SELECT *
FROM News_Table, People_Table
WHERE InStr([News_People_Contributed],CStr([People_ID])) > 0;
This only answers part of the problem: The join -- the issue everyone seemed concerned about in the initial comments. There are not enough details about about the Search_Parameter to provide help on that. Supply more detail if you need more help there.

Add additional columns and subqueries to a MySQL VIEW to create more readable version of an existing table

This problem is really causing me a headache and I have spent hours for different solutions to my problem, but no luck so far.
At our online survey software ("Limesurvey") all data gets stored at a flat table. There is one row for each response data set and each question item has a related column at that table. The actual responses are stored at the table cells. The thing is that this data is hard to read because:
For array questions Limesurvey just stores the answer code -> we also want to add a column for the full answer text.
For multiple numeric questions Limesurvey stores the number inputted -> we also want to add a column listing the related sub-question text.
We are trying to achieve the above by creating a MySQL VIEW based on the table definition of the survey's response table. For that we have extended our VIEW feature to add additional columns when creating the VIEW and we have added code to query the related answer and sub-question texts. Those queries work fine, this is what the VIEW shows if ONE data set is inputted (looks good so far):
One data set
Thing is that once we add a second data set with different answers, the data gets mixed up. It looks like MySQL just aggregates the data from all rows to fill the additional columns. There are now additional answer/sub-question texts at both rows (marked "?") though for that data set no answer was given, see:
Two data sets
My main question is: Is it possible to kind of define the scope for the additional "..._TEXT" columns so they get filled based on details of the current row, not the whole data?
Let me know if you have any questions, it is a little complex to describe this issue.
This is how I would do it. Using joins like this you can see that you are missing a relationship between the main select and the question columns. See the comments in my code below.
CREATE VIEW lime_view_967824 AS
SELECT
ls.id 'id',
ls.submitdate 'submitdate',
ls.lastpage 'lastpage',
ls.startlanguage 'startlanguage',
ls.967824X1087X6950SQ001 'arraySD_SQ001',
COALESCE(a1.answer,'') AS 'arraySD_SQ001[TEXT]',
ls.967824X1087X6950SQ002 'arraySD_SQ002',
COALESCE(a2.answer, '') AS 'arraySD_SQ002[TEXT]',
ls.967824X1087X6950SQ003 'arraySD_SQ003',
COALESCE(a3.answer, '') AS 'arraySD_SQ003[TEXT]',
ls.967824X1087X6946SQ001 'multiOptions_SQ001',
ls.967824X1087X6946SQ002 'multiOptions_SQ002',
ls.967824X1087X6946SQ003 'multiOptions_SQ003',
ls.967824X1087X6946other 'multiOptions_other',
ls.967824X1087X6941SQ001 'multiNumInput_SQ001',
COALESCE(q1.question,'') AS 'multiNumInput_SQ001[TEXT]',
ls.967824X1087X6941SQ002 'multiNumInput_SQ002',
COALESCE(q2.question,'') AS 'multiNumInput_SQ002[TEXT]',
ls.967824X1087X6941SQ003 'multiNumInput_SQ003',
COALESCE(q3.question,'') AS 'multiNumInput_SQ003[TEXT]',
ls.967824X1087X6941SQ004 'multiNumInput_SQ004',
COALESCE(q4.question,'') AS 'multiNumInput_SQ004[TEXT]'
FROM lime_survey_967824 ls
LEFT JOIN lime_answers a1 ON a1.qid=6950 AND a1.language='en' AND ls.967824X1087X6950SQ001=a1.code
LEFT JOIN lime_answers a2 ON a2.qid=6950 AND a2.language='en' AND ls.967824X1087X6950SQ002=a2.code
LEFT JOIN lime_answers a3 ON a3.qid=6950 AND a3.language='en' AND ls.967824X1087X6950SQ003=a3.code
LEFT JOIN lime_questions q1 ON q1.qid=6941 AND q1.title='SQ001' AND q1.language='en' AND q1.type='K' -- no join to ls?
LEFT JOIN lime_questions q2 ON q2.qid=6941 AND q2.title='SQ002' AND q2.language='en' AND q2.type='K' -- no join to ls?
LEFT JOIN lime_questions q3 ON q3.qid=6941 AND q3.title='SQ003' AND q3.language='en' AND q3.type='K' -- no join to ls?
LEFT JOIN lime_questions q4 ON q4.qid=6941 AND q4.title='SQ004' AND q4.language='en' AND q4.type='K' -- no join to ls?

inner query of subqery returning multiple rows

I am not that experience in sql so please forgive if its not a good question to ask,but i researched around almost for 3-4 days but no able to solve.
My problem is i have a table which have multiple image names in it,so what i have to do is whoever is the follower of a particular user i have to get the imaged from this table,so one user there can be multiple followers,so i have to fetch the images posted by all the followers.
Here is the subquery code snippet i am using.
SELECT id,
outfit_image,
img_title,
description
FROM outfitpic_list r2
WHERE Email=ANY(SELECT being_followed
FROM follower_table
WHERE follower='test#gmail.com')
So the inner query here returns multiple values,for each value(being_followed) i have to fetch all the images and display it,but with this query each time i get only one image.I tried IN also but didnot work out.
Table structure:-
Outfitpic_list table
id|outfit_image|datetime|Email|image_title|description
Follower_table
bring_followed|follower
Please help,I am stuck..!!
Thank you..!!
I think your problem may be the = sign between "E-mail" and "Any". Try this statement:
SELECT
id,
outfit_image,
img_title,
description
FROM outfitpic_list r2
WHERE Email IN
(
SELECT being_followed
FROM follower_table
WHERE follower='test#gmail.com'
)
It's the same statement, without the = sign, and the ANY keyword replaced with IN. (I cleaned it up a little to make it more readable)