postgresql: how to SELECT entries that satisfy a condition - php

I am trying to select the entries that have the same text in the "email" column of my postgreSQL table. I am completly new to database and this is the first database I ever created, so sorry if it's a silly question. My database has 3 columns: key, user_mails and json_adress.
I tried
$existent= "SELECT * FROM
(SELECT public.account_recover_users.* AS keys,emails,jsons
FROM public.account_recover_users)
WHERE emails='$email'";
but I guess I am mistaking somewhere.
Please help, I am trying to learn and I got a bit stuck.

The reason you got the error ERROR: subquery in FROM must have an alias Hint: For example, FROM (SELECT ...) [AS] foo is because you have to give an alias (nickname) to any subquery you use. So, just do what the error message hint tells you to do:
"SELECT *
FROM (
SELECT public.account_recover_users.* AS keys, emails, jsons
FROM public.account_recover_users
) as subq
WHERE emails='$email'"
But you don't need a subquery at all. This could be simplified to just:
"SELECT * FROM account_recover_users WHERE user_mails='$email'"
If you want to rename (i.e. give an alias to) your columns upon selection, I wouldn't use a subquery. Try:
"SELECT key as keys, user_mails as emails, json_adress as jsons
FROM account_recover_users
WHERE emails='$email'"
I don't really recommend this, though. If you're just going to give an alias to every column, why not rename the columns in the database?

I am writing another answer, because the currently accepted answer is wrong in several respects. Neither of the two presented queries can work, even though the OP incorrectly accepted the answer.
The original query couldn't work for several reasons:
As was mentioned (and the error message clearly states): a subquery requires an alias.
As was also mentioned, a subquery is just pointless for the simple task.
This construct is nonsense: public.account_recover_users.* AS keys You can't apply an alias after expanding * to the list of columns. Postgres just ignores it. It might throw an exception in future releases.
According to your description, existing columns are named key, user_mails and json_adress (sic!). emails or jsons are just invalid references.
Your absolutely basic query should be:
"SELECT * FROM public.account_recover_users WHERE emails = '$email'"
You can rename columns in the query by appling column aliases, but your WHERE clause cannot refer to output columns (aliases), it has to refer to input columns:
"SELECT key, user_mails AS email, json_adress AS jsons
FROM public.account_recover_users
WHERE user_mails = '$email'"
Detailed explanation in this related answer:
How to re-use result for SELECT, WHERE and ORDER BY clauses?

Because you're referencing public.account_recover_users in a derived table (in brackets), you need to give the derived table an alias which can be almost anything.
$existent= "SELECT * FROM
(SELECT public.account_recover_users.* AS keys,emails,jsons
FROM public.account_recover_users) as aru
WHERE emails='$email'";
In your case though I don't think you need a derived table at all. You could just write.
$existent = "SELECT key as keys, user_mail as emails, json_address as jsons
FROM public.account_recover_users
WHERE emails='$email'";

You don't need the subquery... (Alias it if you actually need one).
Nor do you need public, since it's in your search path by default.
Nor do you need the fields here, since you're selecting them all.
SELECT * FROM account_recover_users WHERE user_mails='$email'
Oh, and don't forget to escape $email... Look into PDO::prepare().

Related

we need to retrieve all the rows from mysql. And table has only a single column e.g name.Which approach is better?

Which of below query will be better to use if table has single column? Please also provide technical justification.
select * from table
or
select `name` from table
Speed/execution be the same. Just because of future table changes (and clarity of the message) you should use second option.
* is just placeholder for all; though there is no difference, because engine treats it like name in that case, but if some day you change table rows (add something, for example surname) it would be best choice, to use just name in select statement due to avoid future source-code changes.

How it works a mysql query with alias?

I'm new in this comunnity and I need to work with a query that get data from a mysql database, I have this query, but I need to add a new table and I don't understand why the query has a alias, I don't know how it works, someone can help me?
This is my query:
SELECT ins.matricula, pe.nombres, pe.appaterno, pe.apmaterno, co.calleynum, co.colonia, co.municipio, co.telfijo, co.telcelular, pe.fechanac, pe.sexo, co.email, pe.institucion, tu.tnombres, tu.tappaterno, tu.tapmaterno, tu.direccion, tu.telefono, ins.fechains, ins.niveledu, ins.fechaini, ins.horario
FROM Inscripciones ins
LEFT JOIN Perfiles pe
ON pe.idperfil=ins.idperfil
LEFT JOIN Contactos co
ON co.idperfil = pe.idperfil
LEFT JOIN Tutores tu
ON tu.matricula = ins.matricula
WHERE pe.idperfil='$var'
I have read the mysql docs but I can't understand how it works.
In MySQL, an "alias" can be declared to simplify the query later.
Typically this is denoted with the "AS" operator, but can also be declared without "AS" - as in your example.
In your example:
SELECT ins.matricula, {...}
FROM Inscripciones ins {...}
The ins is set as an alias for the "Inscripciones" table.
This allows you to use ins throughout the query rather than typing out "Inscripciones." This can be seen in the SELECT statement.
Something to keep in mind - aliases in SQL can be declared after they're first used. This is the case in your example, where SELECT gets ins.matricula before you've actually declared ins as the alias for Inscripciones.
Sometimes this seems counter intuitive, but I promise it will make sense if you experiment with it a bit.
I find it less ambiguous to include the "AS" - which might help it make more sense as you're reading/writing the SQL query.
ex: ... FROM Inscripciones AS ins
To be clear, the use of the alias doesn't change the outcome of your query, but helps you write cleaner queries because you don't have to re-write the tablename every time you want to use it.
A SQL Alias is just what the name says, an alias. It's simply another name (a shorter name) for your table name.
So in your example the table name is Inscripciones, and in this line FROM Inscripciones ins you're saying "ins" is an alias to Inscripciones. Its just a way to make the query smaller/simpler. An alias is like a nickname (i.e. an alias for Michael is "Mike")
Aliases are normally set with "AS" like this:
SELECT * FROM Users AS u
but can be shortened like this:
SELECT * FROM Users u
Tables don't have to have aliases, unless you want to use the same table more than once, but it can make things shorter to type if the tables have columns named the same.
Instead of having to write
SELECT myfulltable1name.id, myfulltable2name.id
You can write
SELECT t1.id, t2.id
(If you've aliased your tables as t1 and t2)
Here's an example query where we use the same table more than once and need an alias to separate them:
SELECT
workAddresses.City as WorkCity,
homeAddresses.City as HomeCity
FROM
Addresses workAddresses
INNER JOIN
Addresses homeAddresses
ON
workAddresses.UserID = homeAddresses.UserID
WHERE
workAddresses.type = 'work' AND
homeAddresses.type = 'home'
Here the Addresses table stores work and home addresses for our users, with a type column to differentiate them. We want a result where tThe work and home address is on the same row, so we have to join the addresses table in twice, we give them sensible aliases so we can tell which is which, and we use where clause to make sure our workAddress table alias only refers to those records with type 'work'
You'll notice I also put an alias on the column names selected, so you can know which is the work City and which is the home city
Sometimes you MUST use an alias, like if you make a subquery, then the result must be aliased in order to be usable:
SELECT
workAddresses.City as WorkCity,
homeAddresses.City as HomeCity
FROM
(SELECT * FROM Addresses WHERE type ='work') workAddresses
INNER JOIN
(SELECT * FROM Addresses WHERE type ='home') homeAddresses
ON
workAddresses.UserID = homeAddresses.UserID
Here we got information from the addresses tables by subquery, and the bracketed sql statements must have aliases
Aliases are always declared at the first point that the object being aliased is brought into the query. For tables, this is in the FROM section, for columns this is in the SELECT section
It might help you to consider it as if the database actually does the from section first, connecting all the tables together, then it does the where, to filter the rows, finally it does the select, to pull just the columns you want. C# has a built in query language called LINQ, that presents things in this more logical way, FROM table WHERE something = something SELECT somecolumns - makes it easier to say "things are aliased when they are first introduced, like variable naming". SQL is what it is, has been for years. You get used to it
Alias in MySQL query is like a temporary short name for your table. They are not necessarily to be used but save your time when you need to create a complex queries. They are mainly used in queries when you use try to fetch data more than 1 table in single query using JOINS.
Suppose you have a table name 'employee_records'. Then trying to fetch the fields for table would look employee_records.id and so on. If you use alias for table name say 'e', then selecting fields will become e.id.
Hope that will make your point clear.
For more information in simple words read about SQL aliases over here - https://www.w3schools.com/sql/sql_alias.asp

How to use SUBSTRING() in mysql WHERE query in php

I have a string in a database field (called term6eyfs) that is made up of numbers -> 555555.
I want to count how many of them have a particular number in a particular position.
I have tried the following code, but I'm met with a Boolean given... error
$pos=2;
$analyse_ot="SELECT COUNT(*) AS ot_count FROM base, users
WHERE base.base_id=$base
AND
users.base_id=$base
AND
users.SUBSTRING(term6eyfs,$pos,1)='4'";
$result_ot=mysqli_query($con,$analyse_ot);
$row_ot = mysqli_fetch_assoc($result_ot);//this is where I get the error
$total_ot= $row_ot['ot_count'];
$otper=($total_ot/$total)*100;
I'm guessing that they way I have constructed my query (particularly the final line) isn't correct, but why?
Based on the additional details you gave in the comment I'd say that is what you are looking for:
SELECT COUNT(*) AS ot_count
FROM base, users
WHERE base.base_id=$base
AND users.base_id=$base
AND SUBSTRING(users.term6eyfs,$pos,1)='4'";
(this assumes that "term6eyfs" is the name of a column in the users table)
The context of this query is unclear. But in general it does make sense to use "parameter binding" to inject php variable values into a query string. You want to read about that, it enhances security and robustness.
Also reconsider if you really want to use the , operator to join those two tables. That operator is extremely slow, usually a LEFT JOIN delivery a much better performance.
Change users.substring() to substring
$analyse_ot="SELECT COUNT(*) AS ot_count FROM base, users
WHERE base.base_id=$base
AND
users.base_id=$base
AND
SUBSTRING(term6eyfs,$pos,1)='4'";

Understanding COUNT() as `count`

I'm currently learning how to build a site in PHP MySQL. However, I seem to fail to understand COUNT() as count and wouldn't mind some further explanation.
I get the principles of COUNT, 0 || 1, and how it returns all the values that pertain to that query.
But, don't see how COUNT as count works. Anyhow, this is how the code I'm writing goes - so we have a working example - and where I first became perplexed.
"SELECT COUNT(id) as count, id
FROM user
WHERE email='$email' AND password='".md5$password."'"
That is what is called alias which is sometimes used to show a more appealing column header to users or the calling code
SELECT COUNT(`id`) as `count`....
will print
count
--------
5
The alias standing as the column header instead of any arbitrary string: See the SQLFiddle to see the difference
From the fiddle you can see that the header column looks somehow e.g.
count(*)
--------
5
With Count() you can count the returning rows of a result set. The also the official MySQL documentation about count:
Databases are often used to answer the question, “How often does a certain type of data occur in a table?” For example, you might want to know how many pets you have, or how many pets each owner has, or you might want to perform various kinds of census operations on your animals.
Counting the total number of animals you have is the same question as “How many rows are in the pet table?” because there is one record per pet. COUNT(*) counts the number of rows, so the query to count your animals looks like this:
SELECT COUNT(*) FROM pet;
The part with AS count means that this colum will get a name which you can use e.g. in PHP. See also this explenation on w3schools:
You can give a table or a column another name by using an alias. This can be a good thing to do if you have very long or complex table names or column names.
An alias name could be anything, but usually it is short.
as count is just an alias. You can use as for any field or method selected. it means you change the name of the column being returned in your dataset.
SELECT `field` as another_name
So:
SELECT COUNT(*) as `count`
Just renames the column from COUNT(*) to count making it easier to work with whereever you are maniuplating your result set.
It also makes for easier access within your current query. Many would do the following with large table names:
SELECT * FROM `table_with_ridiculous_name` as twrn WHERE twrn.id = 1
If you ran this sql:
SELECT COUNT(id), id ....
You would get (after doing a *_fetch_assoc) $row['numberofrecordshere'] which would be very hard to echo (or use in a comparison) unless you knew how many records there would be (which would defeat the purpose of this result, anyway)
Returning it as count allows you to get to it in the resulting array by using $row['count']

Need help querying across two databases (first time trying to do this)

I have two databases I need to work with, db_site and db_forum (these are generic names, FYI).
db_site has a table called main-news, which has a forumurl field which holds a forum thread id and a views field which holds the current pageviews for the article entry in the database. db_forum has a table called forum_threads which has a tid field and a replies field.
I have two things I need to do, one using just the replies and another using the replies and the views. I assume once the former is figured out the latter won't be much more than adding some extra parts, so I'm concerned with the former for the time being.
Not sure how I should approach this since the two tables are in different databases. The login I'm using has access to both of them (AFAIK), so that isn't the problem, it's more of the syntax involved. Would what I'm looking to do be something like this, perhaps?
SELECT
db_forum.forum_threads.replies AS replies
FROM
`db_forum.forum_threads` AS f,
`db_site.main-news` AS s
WHERE
f.tid = s.forumurl
That's a rough guess, from what I can find online abut doing this type of query. Any help is appreciated. :)
First of all, you should indent your SQL code properly. That long line was almost unreadable.
SELECT
db_forum.forum_threads.replies AS replies
FROM
`db_forum.forum_threads` AS f,
`db_site.main-news` AS s
WHERE
f.tid = s.forumurl
Then, make use of your table aliases "f" and "s". You introduced them, so you have to use them:
SELECT
f.replies AS replies
FROM
`db_forum.forum_threads` AS f,
`db_site.main-news` AS s
WHERE
f.tid = s.forumurl
Finally, you should remove the unnecessary quoting:
SELECT
f.replies AS replies
FROM
db_forum.forum_threads AS f,
db_site.main-news AS s
WHERE
f.tid = s.forumurl
If the names of the fields are indicative of their function, then f.tid refers to an identity column while s.forumurl does not. Normally the s.formurl in this case would be a foreign key. Just a guess.

Categories