SQL - AS - table doesn't exist - 1146 - mysql

My query is:
SELECT temp.pid FROM
(SELECT postid, date FROM swapping AS s, post AS p
WHERE s.mid='2' AND p.postid=s.postid) AS temp
WHERE temp.date = (SELECT MAX(date) FROM temp)
I receive #1146 - Table 'databasename.temp' doesn't exist
How can I make it work?
Thank you.

It seems like you want to select the last "pid", in terms of "date", where s.mid='2'
Try this (after you figure out where pid comes from and correct the first line)
SELECT [s? or maybe p?].pid
FROM swapping s INNER JOIN post p ON p.postid=s.postid
WHERE s.mid = '2'
ORDER BY date DESC
LIMIT(0,1)
You might also need to alias the date column in the order by line.

I think you have your column incorrect...
SELECT temp.pid FROM ( SELECT postid, ...
should be
SELECT temp.postid FROM ( SELECT postid, ...

#DRapp hit the nail on the head at least. You haven't selected 'pid' (if that column exists in either the swapping or post table) in your sub selection that your referring to as temp so it would throw some type of error there.

Related

Get Conditionally Latest record from each group - without Aggregate functions or Partition

I have been trying to do this in many ways suggested.
Note: we do not want aggregate function or Partition since this is just a small part of whole Stored procedure and this is client requirement to not have it, so not in option and not possible duplicate of other existing answers / questions
I have a messages table, which has a column from and to, a foreign key to the user table, basically which user sends to whom at simplest. I also have other columns which are isSnoozed and snoozeAt for if the message is snoozed.
So the ordering is according to case. If messages is snoozed then consider snoozeAt time to Order or if not then consider sendAt. (right now we can ignore this condition while ordering, But I mentioned this since we cannot take simply MAX(id) )
I need to get recent most message from messages group by from user id
messages table like :
id -- to -- from -- isSnoozed -- snoozedAt -- sendAt ...
What I tried :
select * from ( select * from messages order by sendAt DESC) as TEMP GROUP BY TEMP.from
I tried many similar approaches but none worked.
I wasted many paid hours but can't find an approach which meets my exact requirement
NOTE: Please ignore typo in query if any, since I cant type in exact query table and names, So i typed in directly here
I figured this out by doing something like this, which could be explained in a simplified way:
select * from message where message.id in (
select
( select id from message where message.from = user.id order by CASE isSnoozed WHEN 0 THEN sendAt ELSE snoozeAt END DESC limit 1) as id
from user where user.id in ( select friends.`whoIsAdded` from friends where friends.`whoAdded` = myId)
) order by CASE isSnoozed WHEN 0 THEN sendAt ELSE snoozeAt END DESC
If I understand correctly, you just want the largest value in one of two columns. Assuming the values are never NULL, you can use greatest():
select m.*
from messages m
where greatest(m.sendAt, m.snoozedAt) =
(select max(greatest(m2.sendAt, m2.snoozedAt))
from messages m2
where m2.from = m.from
);
If the columns can be NULL, then you can use coalesce() to give them more reasonable values.

SQL - Nested query optimization

How can I optimize this query SQL?
CREATE TABLE table1 AS
SELECT * FROM temp
WHERE Birth_Place IN
(SELECT c.DES_COM
FROM tableCom AS c
WHERE c.COD_PROV IS NULL)
ORDER BY Cod, Birth_Date
I think that the problem is the IN clause
First of all it's not quite valid SQL, since you are selecting and sorting by columns that are not part of the group. What you want to do is called "select top N in group", check out Select first row in each GROUP BY group?
Your query doesn't make sense, because you have SELECT * with GROUP BY. Ignoring that, I would recommend writing the query as:
SELECT t.*
FROM temp t
WHERE EXISTS (SELECT 1
FROM tableCom c
WHERE t.Birth_Place = c.DES_COM AND
c.COD_PROV IS NULL
)
ORDER BY Cod, Birth_Date;
For this, I recommend an index on tableCom(desc_com, cod_prov). Your database might also be able to use an an index on temp(cod, birth_date, birthplace).

Set a list in a variable in subquery - MYSQL

My problem is the following, I want set a list of ID in a variable, then use this variable in a subquery. The problem is that WorkBench (my GUI) return the following error : "subquery returning multiple rows". It seems to me that's what I want.
Please explain me where I am wrong.
This is my query :
set #listID := (select ID_VOIE as ID from voies
where ORIGINE = 'XXX'
group by CODE_INSEE, CODE_VOIE
having count(*) > 1);
select substring(v.CODE_INSEE,1,2), count(*) from voies v
where v.ID_VOIE in (#listID)
group by substring(vs.CODE_INSEE,1,2);
The thing is I'm blocked with the "group by", I want do a groupd by after a first group by, that's why I can't (or at least i didn't find a way) write the request with a single WHERE clause.
The thing is I know that I can put the whole request directly in my subquery instead of using variable but :
It can let me use this trick in another requests that needed this behaviour (DRY concept !)
I'm not sure but the subquery will be executed in each turn of my loop, and that will be very inefficient
So I seek 2 possible ways : a way that let me use a list in a variable in a subquery OR a way that let me use "group by" twice in a single query.
Thanks you in advance for your answers (oh and sorry for my english, this is not my maternal language).
Unless you need that variable for something else, you should be able to skip it entirely as follows:
SELECT
SUBSTRING(v.CODE_INSEE,1,2),
COUNT(*)
FROM
voies v
WHERE
v.ID_VOIE in
(SELECT
ID_VOIE as ID
FROM
voies
WHERE
ORIGINE = 'XXX'
GROUP BY
CODE_INSEE,
CODE_VOIE
HAVING COUNT(*) > 1)
GROUP BY
SUBSTRING(vs.CODE_INSEE,1,2);
As you say, the subquery will be executed for all rows. To avoid that, a variable would be best, but MySQL doesn't support table variables. Instead, you can use a temporary table:
IF EXISTS DROP TABLE myTempTable;
CREATE TEMPORARY TABLE myTempTable (ID_VOIE int); -- I don't know the datatype
INSERT INTO myTempTable (ID_VOIE)
SELECT DISTINCT -- using distinct so I can join instead of use IN.
ID_VOIE as ID from voies
WHERE
ORIGINE = 'XXX'
GROUP BY
CODE_INSEE, CODE_VOIE
HAVING COUNT(*) > 1
And now you can do this:
SELECT
SUBSTRING(v.CODE_INSEE,1,2), COUNT(*)
FROM
voies v
JOIN myTempTable tt ON
v.ID_VOIE = tt.ID_VOIE
GROUP BY SUBSTRING(vs.CODE_INSEE,1,2);

Two Queries on same table showing same row with different values?

I'm new to SQL, but I'm pretty sure something strange is happening here. I have a MySQL database with a table (eventtable) with 4 columns (RoomNum, EventName, EventStatus, EventDateTime).
Certain EventNames repeat with the EventStatus toggling ON and OFF at different times. I'm trying to get the latest entry so that I have the "current" state, so I use:
select RoomNum, EventName, EventStatus, max(EventDateTime) as MaxDate
from eventtable where eventName = "DND"
group by RoomNum
Resulting in:
Just to make sure everything is ok, I check each room to make sure it is giving the latest one with:
SELECT * FROM `eventtable`
where RoomNum = "070#" and eventname = "DND" /*where "#" is a specific digit*/
order by eventdatetime asc
The first one looked good:
But then the others don't! (The EventStatus is wrong even though the time is correct):
what I don't get is that EventDateTime matches which tells me I'm looking at the same row of data, but then how can the internal value (EventStatus) be different?
Please help. Thank you.
By using below query, You can get the result as per your requirement. Please try.
select * from(select RoomNum, EventName, EventStatus, EventDateTime from eventtable where eventName = "DND" order by EventDateTime desc)tab group by RoomNum ;
This is why firebird does not allow this. Only this is valid
select RoomNum, max(EventDateTime) as MaxDate
from eventtable where eventName = "DND"
group by RoomNum
EventName and EventStatus values are arbitrary. You have not told it which ones you want. And I don't think you can. RoomNumn is implicit because of "group by".
To get the data you want, one way would be to use a subselect where the max(EventDateTime) returns a reference.

Select data from another table with where clause

What's wrong with this query, im selecting data from 3 different tables here. First title of exam from "class_exams" table , second selecting sum of total marks from "results" table. Query works fine without where clause.
SELECT id, exam_date , (
SELECT title
FROM class_exams
WHERE result_heads.exam_id = class_exams.id
) AS exam_title, (
SELECT sum( marks )
FROM results
WHERE result_heads.id = results.head_id
) AS obt_marks
FROM `result_heads` WHERE exam_title = 'test';
Error comes
Unknown column 'exam_title' in 'where clause'
Consider using Join
If I understand the table schema , it should be like this :
SELECT result_heads.id, result_heads.exam_date , sum( results.marks )AS obt_marks
FROM results JOIN result_heads
ON results.exam_id = result_heads.id
GROUP BY result_heads.id, result_heads.exam_date
I think you need to add the name of table in where clouse
WHERE `tbl_name`.`exam_title = 'test';
I know this is an old post, but I like to fill the answers where old posts end to prevent dead end posting. It looks like the table name is not being called out in the From clause
See this link http://www.techonthenet.com/mysql/where.php and look at the example - Joining Tables.