Add table to query - postgresql

I have query where I select id_categories and categories_names, now I added new table categories_description, same as categories_names but with descriptions (of course it has id_category too), how to modify this query to select k.id_category, kn.name and my new category_description from my new table categories_descriptions (sometimes there is no description for category).
SELECT
c.id_category,
cn.name,
FROM
categories c,
categories_names cn
WHERE
c.id_category = cn.id_category
I am using PostgreSQL but I think in MySQL it will be the same.

You mentioned that sometimes the description is missing so LEFT JOIN should be suitable:
SELECT c.id_category,
cn.name,
cd.category_description
FROM
categories c
JOIN categories_names cn ON c.id_category = cn.id_category
LEFT JOIN categories_descriptions cd ON cn.id_category = cd.id_category

Related

How to give alias for columns with same name after joining two tables in Postgres

Hi Guys I'm doing inner join for two tables and selecting all the columns from both tables. But I'm getting three cols with same name like id, created_at and updated_at.
Query:
SELECT addresses.* , facilities.* FROM facilities
INNER JOIN addresses
ON facilities.main_address_id = addresses.id
Is there any possible way that I can mention alias for above cols having same name while selecting all cols with * ?
Help of any kind would be appreciated! Thanks!
No you can't do this other than aliasing each column separately.
But if your query will be repetitive you could create VIEW:
CREATE OR REPLACE VIEW facilities_addresses AS
SELECT
addresses.column AS "addresses_column",
facilities.column AS "facilities_column"
FROM facilities
INNER JOIN addresses ON (facilities.main_address_id = addresses.id)
and then you can query:
SELECT * FROM facilities_addresses
yes you can
SELECT
addr.id as addressesId ,
addr.created_at as addresses_created_at,
addr.updated_at as addresses_update_at,
fac.id as facilitiesId,
fac.created_at as facilities_created_at,
fac.updated_at as facilities_updated_at FROM facilities as fac
INNER JOIN addresses as addr
ON facilities.main_address_id = addresses.id

How to use GROUP BY with Firebird?

I'm trying create a SELECT with GROUP BY in Firebird but I can't have any success. How could I do this ?
Exception
Can't format message 13:896 -- message file C:\firebird.msg not found.
Dynamic SQL Error.
SQL error code = -104.
Invalid expression in the select list (not contained in either an aggregate function or the GROUP BY clause).
(49,765 sec)
trying
SELECT FA_DATA, FA_CODALUNO, FA_MATERIA, FA_TURMA, FA_QTDFALTA,
ALU_CODIGO, ALU_NOME,
M_CODIGO, M_DESCRICAO,
FT_CODIGO, FT_ANOLETIVO, FT_TURMA
FROM FALTAS Falta
INNER JOIN ALUNOS Aluno ON (Falta.FA_CODALUNO = Aluno.ALU_CODIGO)
INNER JOIN MATERIAS Materia ON (Falta.FA_MATERIA = Materia.M_CODIGO)
INNER JOIN FORMACAOTURMAS Turma ON (Falta.FA_TURMA = Turma.FT_CODIGO)
WHERE (Falta.FA_CODALUNO = 238) AND (Turma.FT_ANOLETIVO = 2015)
GROUP BY Materia.M_CODIGO
Simple use of group by in firebird,group by all columns
select * from T1 t
where t.id in
(SELECT t.id FROM T1 t
INNER JOIN T2 j ON j.id = t.jid
WHERE t.id = 1
GROUP BY t.id)
Using GROUP BY doesn't make sense in your example code. It is only useful when using aggregate functions (+ some other minor uses). In any case, Firebird requires you to specify all columns from the SELECT column list except those with aggregate functions in the GROUP BY clause.
Note that this is more restrictive than the SQL standard, which allows you to leave out functionally dependent columns (ie if you specify a primary key or unique key, you don't need to specify the other columns of that table).
You don't specify why you want to group (because it doesn't make much sense to do it with this query). Maybe instead you want to ORDER BY, or you want the first row for each M_CODIGO.

Specifice order to tables in postgres

I just created a temporary table as:
create temporary table userAndProductSales as
select p.p_name, u.u_name, u.s_price, u.quantity
from product p
join userAndStates u
on p.s_id = u.s_id
Now I want to select some columns with a particular order. For example, I want the select to give me an output of:
u_name1 p_name1
u_name1 p_name2
u_name1 p_name3
u_name1 p_name4
...
u_name2 p_name1
u_name2 p_name2
u_name2 p_name3
....
and so on and so forth. How do I get this ouput? I've tried something on the lines of:
select (select u_name from userandproductsales order by u_name), p_name from userandproductsales
but I'm getting an error
UPDATE: Figured out that the table I'm joining isn't giving me the correct data I want. Thanks for the help though.
Here is how to use ORDER BY :
SELECT * from userandstatesales
order by u_name , p_name
Unless there is a reason for creating a temporary table (like needing to access it later in the same session), you should avoid the expense and simply do a order by from your select. For example:
select p.p_name, u.u_name, u.s_price, u.quantity
from product p
join userAndStates u
on p.s_id = u.s_id
order by u.u_name, p.p_name;

How to do this JOIN

Related to my previous post here, I have the following SELECT:
SELECT tc.[Time],tc.[From], tc.[To], tc.[Cost], tc.[Length], tc.[Type], tc.[PlaceCalled]
FROM
TelstraCall as tc
WHERE
[AccountNumber] IN (#AccountNumber)
ORDER BY [Time] DESC
I'm trying to get the [Username] out of [Resource] given that the [PhoneNum] in [rtc] matches either [From] or [To], and Hogan has kindly helped me out with the first half :
USE [rtc]
SELECT [Username]
FROM [dbo].[Resource] R
JOIN ResourcePhone RP on R.ResourceId = RP.ResourceId
WHERE RP.PhoneNum = tc.[From]
Now I'm trying to work out the syntax of how to get a 'User1' given that [From] matches the [PhoneNum] in [rtc] and a 'User2' if [To] matches [PhoneNum] instead, because I can't have them being jumbled up.
What you're wanting to do is join on the same table twice to get related values based on two different references.
For this, you use table aliases. Here's a simple example
SELECT u1.[Username] AS User1, u2.[Username] AS User2
FROM TelstraCall tc
INNER JOIN ResourcePhone rp1 ON tc.[From] = rp1.PhoneNum
INNER JOIN Resource u1 ON rp1.ResourceId = u1.Id -- guessing at column names here
INNER JOIN ResourcePhone rp2 ON tc.[To] = rp2.PhoneNum
INNER JOIN Resource u2 ON rp2.ResourceId = u2.Id
Here is one way that you can do this using CROSS APPLY since you are using SQL Server 2008. CROSS APPLY helps you to join your table with sub queries.
In this case, the table CallDetails in the database PhoneBills drives your query using the fields From and To. Both these fields have to fetch the Username data from the table Resource in the database rtc by joining with the PhoneNumber column in the table ResourcePhone also in the database rtc.
So the inner/sub query will join the tables Resource and ResourcePhone, it will then be used twice to fetch User1 and User2. For User1, the filter will use the From field in the table CallDetails in the database PhoneBills and for User2, the filter will use the To field in the table CallDetails in the database PhoneBills
SELECT USR1.UserName AS [User1]
, USR2.UserName AS [User2]
FROM PhoneBills.dbo.CallDetails CD
CROSS APPLY (
SELECT Username
FROM rtc.dbo.Resource R
INNER JOIN rtc.dbo.ResourcePhone RP
ON RP.ResourceID = R.ResourceID
WHERE RP.PhoneNumber = CD.From
) USR1
CROSS APPLY (
SELECT Username
FROM rtc.dbo.Resource R
INNER JOIN rtc.dbo.ResourcePhone RP
ON RP.ResourceID = R.ResourceID
WHERE RP.PhoneNumber = CD.To
) USR2

Joining several tables: table specified more than once error

I am attempting to call data after joining all of my tables in a postgreSQL query.
I am getting the following error:
Error in postgresqlExecStatement(conn, statement, ...) :
RS-DBI driver: (could not Retrieve the result : ERROR: table name "place" specified more than once
)
Failed to execute SQL chunk
After referring to similar posts and online resources, I have attempted setting aliases (which only create new errors about not referring to the other tables in the FROM clause), reordering the table names (the cleanest, reordered chunk is posted below), and experimenting with UPDATE/FROM/JOIN as an alternative to SELECT/FROM/JOIN. However, I think I ultimately need to be using the SELECT clause.
SELECT *
FROM place
INNER JOIN place ON place.key = form.key
INNER JOIN form ON form.id = items.formid
INNER JOIN items ON items.recid = rec.id
INNER JOIN rec ON rec.id = sub.recid
INNER JOIN sub ON sub.id = type.subid
INNER JOIN type ON type.name = det.typeid;
You have "place" in your query twice, which is allowed but you would have to alias the second use of the table "place". Also you reference something called "det", but it's not a table or alias anywhere in your query. If you want only one place that's fine, just remove the INNER JOIN place and move your place.key = form.key to the form join or to a where clause.
If you want to place tables in their because you are trying to join the table to itself the alias the second one, but you will want to make sure that you then have a clause to join those two tables on (could be part of an on or a where)
The issue ended up being the order of table names. The code below joined everything just fine:
SELECT *
FROM place
INNER JOIN form ON place.key = form.key
INNER JOIN items ON form.id = items.formid
INNER JOIN rec ON items.recid = rec.id
INNER JOIN sub ON rec.id = sub.recid
INNER JOIN type ON sub.id = type.subid
INNER JOIN det ON type.name = det.typeid;