Cannot retrieve data from database - Error 1241 - php

Error
SQL query: Documentation
SELECT status.id AS id, status.status
FROM STATUS
WHERE id
IN (
SELECT student.id, student.fname
FROM student,
STATUS WHERE student.id =14
)
ORDER BY status_id DESC
MySQL said: Documentation
#1241 - Operand should contain 1 column(s)

The SELECT inside the IN() should not select more than one column.

in the subuery "SELECT student.id, student.fname" you have to extract only one field

Related

Select most common value? [duplicate]

How can I find the most frequent value in a given column in an SQL table?
For example, for this table it should return two since it is the most frequent value:
one
two
two
three
SELECT
<column_name>,
COUNT(<column_name>) AS `value_occurrence`
FROM
<my_table>
GROUP BY
<column_name>
ORDER BY
`value_occurrence` DESC
LIMIT 1;
Replace <column_name> and <my_table>. Increase 1 if you want to see the N most common values of the column.
Try something like:
SELECT `column`
FROM `your_table`
GROUP BY `column`
ORDER BY COUNT(*) DESC
LIMIT 1;
Let us consider table name as tblperson and column name as city. I want to retrieve the most repeated city from the city column:
select city,count(*) as nor from tblperson
group by city
having count(*) =(select max(nor) from
(select city,count(*) as nor from tblperson group by city) tblperson)
Here nor is an alias name.
Below query seems to work good for me in SQL Server database:
select column, COUNT(column) AS MOST_FREQUENT
from TABLE_NAME
GROUP BY column
ORDER BY COUNT(column) DESC
Result:
column MOST_FREQUENT
item1 highest count
item2 second highest
item3 third higest
..
..
For use with SQL Server.
As there is no limit command support in that.
Yo can use the top 1 command to find the maximum occurring value in the particular column in this case (value)
SELECT top1
`value`,
COUNT(`value`) AS `value_occurrence`
FROM
`my_table`
GROUP BY
`value`
ORDER BY
`value_occurrence` DESC;
Assuming Table is 'SalesLT.Customer' and the Column you are trying to figure out is 'CompanyName' and AggCompanyName is an Alias.
Select CompanyName, Count(CompanyName) as AggCompanyName from SalesLT.Customer
group by CompanyName
Order By Count(CompanyName) Desc;
If you can't use LIMIT or LIMIT is not an option for your query tool. You can use "ROWNUM" instead, but you will need a sub query:
SELECT FIELD_1, ALIAS1
FROM(SELECT FIELD_1, COUNT(FIELD_1) ALIAS1
FROM TABLENAME
GROUP BY FIELD_1
ORDER BY COUNT(FIELD_1) DESC)
WHERE ROWNUM = 1
If you have an ID column and you want to find most repetitive category from another column for each ID then you can use below query,
Table:
Query:
SELECT ID, CATEGORY, COUNT(*) AS FREQ
FROM TABLE
GROUP BY 1,2
QUALIFY ROW_NUMBER() OVER(PARTITION BY ID ORDER BY FREQ DESC) = 1;
Result:
Return all most frequent rows in case of tie
Find the most frequent value in mysql,display all in case of a tie gives two possible approaches:
Scalar subquery:
SELECT
"country",
COUNT(country) AS "cnt"
FROM "Sales"
GROUP BY "country"
HAVING
COUNT("country") = (
SELECT COUNT("country") AS "cnt"
FROM "Sales"
GROUP BY "country"
ORDER BY "cnt" DESC,
LIMIT 1
)
ORDER BY "country" ASC
With the RANK window function, available since MySQL 8+:
SELECT "country", "cnt"
FROM (
SELECT
"country",
COUNT("country") AS "cnt",
RANK() OVER (ORDER BY COUNT(*) DESC) "rnk"
FROM "Sales"
GROUP BY "country"
) AS "sub"
WHERE "rnk" = 1
ORDER BY "country" ASC
This method might save a second recount compared to the first one.
RANK works by ranking all rows, such that if two rows are at the top, both get rank 1. So it basically directly solves this type of use case.
RANK is also available on SQLite and PostgreSQL, I think it might be SQL standard, not sure.
In the above queries I also sorted by country to have more deterministic results.
Tested on SQLite 3.34.0, PostgreSQL 14.3, GitHub upstream.
Most frequent for each GROUP BY group
MySQL: MySQL SELECT most frequent by group
PostgreSQL:
Get most common value for each value of another column in SQL
https://dba.stackexchange.com/questions/193307/find-most-frequent-values-for-a-given-column
SQLite: SQL query for finding the most frequent value of a grouped by value
SELECT TOP 20 WITH TIES COUNT(Counted_Column) AS Count, OtherColumn1,
OtherColumn2, OtherColumn3, OtherColumn4
FROM Table_or_View_Name
WHERE
(Date_Column >= '01/01/2023') AND
(Date_Column <= '03/01/2023') AND
(Counted_Column = 'Desired_Text')
GROUP BY OtherColumn1, OtherColumn2, OtherColumn3, OtherColumn4
ORDER BY COUNT(Counted_Column) DESC
20 can be changed to any desired number
WITH TIES allows all ties in the count to be displayed
Date range used if date/time column exists and can be modified to search a date range as desired
Counted_Column 'Desired_Text' can be modified to only count certain entries in that column
Works in INSQL for my instance
One way I like to use is:
select *<given_column>*,COUNT(*<given_column>*)as VAR1 from Table_Name
group by *<given_column>*
order by VAR1 desc
limit 1

mysql update subquery not working

mysql update syntax doesn't seem to work when I added the subquery.
Are there restrictions on subqueries on update syntax?
doesn't work:
update books set imagename ='name'
where book_ID='(select book_ID from books order by book_ID desc limit 1)';
works:
update books set imagename ='name'
where book_ID='101';
MySQL does have limits on subqueries using the table being updated. So yours is not allowed:
update books
set imagename ='name'
where book_ID = (select book_ID from books order by book_ID desc limit 1);
Instead, you can do:
update books
set imagename ='name'
order by book_ID desc
limit 1;
Here is the explanation in the documentation:
In general, you cannot modify a table and select from the same table
in a subquery. For example, this limitation applies to statements of
the following forms:
DELETE FROM t WHERE ... (SELECT ... FROM t ...);
UPDATE t ... WHERE col = (SELECT ... FROM t ...);
{INSERT|REPLACE} INTO t (SELECT ... FROM t ...);
Exception: The preceding prohibition does not apply if you are using a subquery for the modified table in the FROM clause. Example:
UPDATE t ... WHERE col = (SELECT * FROM (SELECT ... FROM t...) AS _t ...);
Here the result from the subquery in the FROM clause is stored as a temporary table, so the relevant rows in t have already been
selected by the time the update to t takes place.
Try This query.
Update books
Set imagename = name"
Where book_ID In (
Select T1.book_ID
From books As T1
Where T1.book_ID = '101'
)

MySQL Error in Nested Query

I have the following code in PHP:
SELECT (
SELECT (
SELECT `forum_posts.id`,`forum_posts.author`,`forum_posts.author_id`, `forum_boards.date`, MIN(`forum_posts.date`) FROM `forum_posts`
WHERE `parent` IN
(SELECT `id` FROM `forum_boards` WHERE `parent`="'.Oflow(intval((isset($_GET['id']) ? $_GET['id'] : '0'))).'")
INNER JOIN `forum_boards`
ON `forum_boards.id`=`forum_posts.id`
ORDER BY `update_date` DESC
LIMIT 1
GROUP BY `parent`;
) ORDER BY `order_large`,`order`;
) UNION (
SELECT `name`,`id`,`info`,`parent_name` FROM `forum_boards` WHERE `parent`="'.Oflow(intval((isset($_GET['id']) ? $_GET['id'] : '0'))).'" ORDER BY `order_large`,`order
)
This is a script to get a list of boards and posts in a forum system. What it's supposed to do is get data from a table "boards" and "posts". It then tries to find the most recent post in the sub-board of the board currently being viewed. Then, it tries to join the "parent" and board "id" togeather, in order that the columns can be matched and the posts be sorted accordingly. Finally, a UNION is performed to combine the newly found and ordered posts with the actual forum data.
The error:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'INNER JOIN forum_boards ON forum_boards.id=forum_posts.id ORDER BY' at line 7
The problem is, it don't work! I've double checked every column and table name, and they all exist. This is a very "alpha" code, so if you have any efficiency tips that's be great.
You can't INNER JOIN in the WHERE clause which is what your query is trying to do
SELECT (
SELECT (
SELECT `forum_posts.id`,`forum_posts.author`,`forum_posts.author_id`, `forum_boards.date`, MIN(`forum_posts.date`) FROM `forum_posts`
WHERE `parent` IN
(SELECT `id` FROM `forum_boards` WHERE `parent`="'.Oflow(intval((isset($_GET['id']) ? $_GET['id'] : '0'))).'")
INNER JOIN `forum_boards` ## This is effectively JOINing within a WHERE clause
ON `forum_boards.id`=`forum_posts.id`
ORDER BY `update_date` DESC
LIMIT 1
GROUP BY `parent`;
) ORDER BY `order_large`,`order`;
) UNION (
SELECT `name`,`id`,`info`,`parent_name` FROM `forum_boards` WHERE `parent`="'.Oflow(intval((isset($_GET['id']) ? $_GET['id'] : '0'))).'" ORDER BY `order_large`,`order
)
You might need to rethink your query a little bit.

Mysql error in a count query which counts a union subquery

Can you please check this mysql query and maybe help with what's wrong with it?
When I run it through mysql as my host i get this error:
#1248 - Every derived table must have its own alias
Here is the code:
mysql_query("
SELECT COUNT(*)
FROM
(
(SELECT 1 as sort_col,id,pic0 FROM `cronjob_reloaded` WHERE id IS NOT NULL AND id LIKE '%car%')
UNION
(SELECT 2 as sort_col,id,pic0 FROM `cronjob_reloaded` WHERE id IS NOT NULL AND category IN ('bmw'))
ORDER BY sort_col
)
")
Ty!
PS. I have posted an unclear question some time ago, can a admin please delete that one? And sorry for any inconvenience. The question is here
As the error says, derived tables must be aliased.
SELECT COUNT(*)
FROM
(
(SELECT 1 as sort_col,id,pic0 FROM `cronjob_reloaded` WHERE id IS NOT NULL AND id LIKE '%car%')
UNION
(SELECT 2 as sort_col,id,pic0 FROM `cronjob_reloaded` WHERE id IS NOT NULL AND category IN ('bmw'))
ORDER BY sort_col
) q /* I added the alias "q" */

unique field from mysql database to php

I have a sample database like this, in which, id is always unique, but the user_id is not unique.
id,user_id,message,msg_datetime
111,u1, msg from u1,time present here
112,u2, msg from u2,time present here
113,u3, msg from u3,time present here
114,u2, msg from u2,time present here
115,u7, msg from u7,time present here
116,u2, msg from u2,time present here
117,u1, msg from u1,time present here
118,u5, msg from u5,time present here
so i want to grab only those unique users who have messaged and order them in DESC by msg_datetime.
This is the query i have.
select id,DISTINCT user_id,msg_datetime ORDER BY msg_datetime DESC but i am getting an error as:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DISTINCT. any help here? what is the correct syntax for what i am trying to achieve?
I want to show only one entry for each user, it does not matter which ID i am showing but only 1 per user.
If you don't care which record with the same user_id query should return, then
SELECT id,user_id,msg_datetime FROM table_1 GROUP BY user_id ORDER BY msg_datetime DESC
If you want to display, for instance, the last record for each user, you need
SELECT a.user_id, a.last_time, b.id
FROM
(SELECT user_id, MAX(msg_datetime) as last_time
FROM table1)a
INNER JOIN table1 b ON (b.user_id = a.user_id AND b.msg_datetime = a.last_time)
ORDER BY a.last_time;
SELECT syntax:
SELECT (fieldlists)
FROM (table)
[WHERE (conditions)]
ORDER BY (something)
You kindof forgot to say which table you want the data from.
You misunderstand how DISTINCT works. It works on rows not fields. What you want is a groupwise maximum, also known as greatest-n-per-group.
Here's one way to do it in MySQL:
SELECT id, user_id, message, msg_datetime
FROM (
SELECT
id, user_id, message, msg_datetime,
#rn := CASE WHEN #prev_user_id = user_id
THEN #rn + 1
ELSE 1
END AS rn,
#prev_user_id := user_id
FROM (SELECT #prev_user_id := NULL) vars, Table1 T1
ORDER BY user_id, msg_datetime DESC
) T2
WHERE rn = 1
ORDER BY msg_datetime

Categories