Select data from another table with where clause - mysql

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.

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.

Unknown column 'wp_cons_users.id' in 'on clause'

I have three table one is for users and other one is for subject and third one contain user_id, subject_id foreign keys.
I get unknow coloumn when I run the following sql.
SELECT wp_cons_users.first_name, wp_cons_subject.subject, wp_cons_skilllist.skill_level
FROM `wp_cons_subject`
JOIN wp_cons_skilllist ON wp_cons_skilllist.user_id = wp_cons_users.id
JOIN wp_cons_users ON wp_cons_users.id = wp_cons_skilllist.user_id
WHERE wp_cons_subject.id = '1'
ORDER BY `wp_cons_skilllist`.`skill_level` DESC
I can't find the error with this query.
wp_cons_skilllist
column link to
id (primay)
user_id wp_cons_users -> id
subj_id wp_cons_subject -> id
skill_level
Here I try to get the username, skill level and subject for any given subject id.
Looks like your main problem is with the ordering of your JOINs. In your first join, you are matching with wp_cons_users.id, but you don't join that table until later in the query. If you re-order the joins it should work better. Also, based on your table description, it seems that you will also need to join on subject_id. This query should help:
SELECT wp_cons_users.first_name
, wp_cons_subject.subject
, wp_cons_skilllist.skill_level
FROM wp_cons_users
JOIN `wp_cons_subject`
ON wp_cons_users.id=`wp_cons_subject`.user_id
AND wp_cons_subject.id = '1'
JOIN
wp_cons_skilllist
ON wp_cons_skilllist.user_id = wp_cons_users.id
AND wp_cons_skilllist.subject_id = `wp_cons_subject`.id
ORDER BY `wp_cons_skilllist`.`skill_level` DESC
I am guessing about the field names that weren't in your original query, so you may have to make some changes if they're different from what I'm assuming.
Without information about your attributes in your table, I'm afraid we can only assume that there is no ID column in your wp_cons_users table.
when I corrected the query to following it started to work.
SELECT wp_cons_users.first_name, wp_cons_subject.subject, wp_cons_skilllist.skill_level
FROM `wp_cons_skilllist`
JOIN wp_cons_subject ON wp_cons_subject.id = wp_cons_skilllist.subject_id
JOIN wp_cons_users ON wp_cons_users.id = wp_cons_skilllist.user_id
WHERE wp_cons_skilllist.subject_id = '1'
ORDER BY `wp_cons_skilllist`.`skill_level` DESC
LIMIT 0 , 30

Get a list of ids not present in a table

I have a list of ids, and I want to query a mysql table for ids not present in the table.
e.g.
list_of_ids = [1,2,4]
mysql table
id
1
3
5
6
..
Query should return [2,4] because those are the ids not in the table
since we cant view ur code i can only work on asumption
Try this anyway
SELECT id FROM list_of_ids
WHERE id NOT IN (SELECT id
FROM table)
I hope this helps
There is a horrible text-based hack:
SELECT
substr(result,2,length(result)-2) AS notmatched
FROM (
SELECT
#set:=replace(#set,concat(',',id,','),',') AS result
FROM (
select #set:=concat(',',
'1,2,4' -- your list here
,',')
) AS setinit,
tablename --Your tablename here
) AS innerview
ORDER BY LENGTH(result)
LIMIT 1;
If you represent your ids as a derived table, then you can do this directly in SQL:
select list.val
from (select 1 as val union all
select 2 union all
select 4
) list left outer join
t
on t.id = list.val
where t.id is null;
SQL doesn't really have a "list" type, so your question is ambiguous. If you mean a comma separated string, then a text hack might work. If you mean a table, then something like this might work. If you are constructing the SQL statement, I would advise you to go down this route, because it should be more efficient.

SQL - AS - table doesn't exist - 1146

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.

Update with SELECT and group without GROUP BY

I have a table like this (MySQL 5.0.x, MyISAM):
response{id, title, status, ...} (status: 1 new, 3 multi)
I would like to update the status from new (status=1) to multi (status=3) of all the responses if at least 20 have the same title.
I have this one, but it does not work :
UPDATE response SET status = 3 WHERE status = 1 AND title IN (
SELECT title FROM (
SELECT DISTINCT(r.title) FROM response r WHERE EXISTS (
SELECT 1 FROM response spam WHERE spam.title = r.title LIMIT 20, 1)
)
as u)
Please note:
I do the nested select to avoid the famous You can't specify target table 'response' for update in FROM clause
I cannot use GROUP BY for performance reasons. The query cost with a solution using LIMIT is way better (but it is less readable).
EDIT:
It is possible to do SELECT FROM an UPDATE target in MySQL. See solution here
The issue is on the data selected which is totaly wrong.
The only solution I found which works is with a GROUP BY:
UPDATE response SET status = 3
WHERE status = 1 AND title IN (SELECT title
FROM (SELECT title
FROM response
GROUP BY title
HAVING COUNT(1) >= 20)
as derived_response)
Thanks for your help! :)
MySQL doesn't like it when you try to UPDATE and SELECT from the same table in one query. It has to do with locking priorities, etc.
Here's how I would solve this problem:
SELECT CONCAT('UPDATE response SET status = 3 ',
'WHERE status = 1 AND title = ', QUOTE(title), ';') AS sql
FROM response
GROUP BY title
HAVING COUNT(*) >= 20;
This query produces a series of UPDATE statements, with the quoted titles that deserve to be updated embedded. Capture the result and run it as an SQL script.
I understand that GROUP BY in MySQL often incurs a temporary table, and this can be costly. But is that a deal-breaker? How frequently do you need to run this query? Besides, any other solutions are likely to require a temporary table too.
I can think of one way to solve this problem without using GROUP BY:
CREATE TEMPORARY TABLE titlecount (c INTEGER, title VARCHAR(100) PRIMARY KEY);
INSERT INTO titlecount (c, title)
SELECT 1, title FROM response
ON DUPLICATE KEY UPDATE c = c+1;
UPDATE response JOIN titlecount USING (title)
SET response.status = 3
WHERE response.status = 1 AND titlecount.c >= 20;
But this also uses a temporary table, which is why you try to avoid using GROUP BY in the first place.
I would write something straightforward like below
UPDATE `response`, (
SELECT title, count(title) as count from `response`
WHERE status = 1
GROUP BY title
) AS tmp
SET response.status = 3
WHERE status = 1 AND response.title = tmp.title AND count >= 20;
Is using GROUP BY really that slow ? The solution you tried to implement looks like requesting again and again on the same table and should be way slower than using GROUP BY if it worked.
This is a funny peculiarity with MySQL - I can't think of a way to do it in a single statement (GROUP BY or no GROUP BY).
You could select the appropriate response rows into a temporary table first then do the update by selecting from that temp table.
you'll have to use a temporary table:
create temporary table r_update (title varchar(10));
insert r_update
select title
from response
group
by title
having count(*) < 20;
update response r
left outer
join r_update ru
on ru.title = r.title
set status = case when ru.title is null then 3 else 1;