Get Seperate Total of Two MySQL table - mysql

I have two table called questions and entries. I want get separate total of both table using one query. Like questions 10 and entries 20. I have tried like below but its giving me two row as totalEntries
SELECT COUNT(*) as totalEntries FROM quiz_entries UNION SELECT COUNT(*) as totalQuestions FROM quiz_questions
Let me know if any one can help me for get seperate result for both table like totalEntries 20 and totalQuestions 10.
Thanks!

Use each query as an expression that returns the number of rows in each table in a SELECT statement:
SELECT
(SELECT COUNT(*) FROM quiz_entries) as totalEntries,
(SELECT COUNT(*) FROM quiz_questions) as totalQuestions

You can do by this also. Because temp table solves our complex problem too.
IF(OBJECT_ID('tempdb..#tblEntries')) IS NOT NULL
DROP TABLE #tblEntries
IF(OBJECT_ID('tempdb..#tblQuestions')) IS NOT NULL
DROP TABLE #tblQuestions
DECLARE #quizEntriesCount INT
DECLARE #quizQuestionsCount INT
SET #quizEntriesCount = (SELECT COUNT(1) FROM quiz_entries)
SET #quizQuestionsCount =(SELECT COUNT(1) FROM quiz_questions)
SELECT #quizEntriesCount AS quizEntriesCount, #quizQuestionsCount AS quizQuestionCount,

Related

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).

Returning all records from derived table name that also have IN statements

I'm trying to retrieve a single record from my database, BUT I don't know which table name to query until I query another record.
If I knew the table name and ID the end query would look something like this.
SELECT * FROM `materials_sheet_stock` WHERE `id` = 2
But since I do NOT know the table name or the ID in that table I'm trying to break it up a bit.
This query will successfully retrieve the table name for the above query
SELECT tb1.*
FROM (SELECT `tag_table`
FROM `materials_group_tags_mapping`
WHERE `tag_id` IN
(SELECT `materials_group_tags`.`id`
FROM `materials_group_tags`
WHERE `materials_group_tags`.`name` = "frameless_base_side_material_unexposed")) AS tb1
which in this case is materials_sheet_stock
This query will successfully retrieve the ID that I need for the above query
(SELECT `materials_group_tags_mapping`.`tag_value`
FROM `materials_group_tags_mapping`
WHERE `materials_group_tags_mapping`.`tag_id` IN
(SELECT `materials_group_tags`.`id`
FROM `materials_group_tags`
WHERE `materials_group_tags`.`name` = "frameless_base_side_material_unexposed"))
But now when I put them all together in 1 query using IN it keeps throwing errors about not finding columns, or that all tables need an alias. I've tried editing the following code for like an hour with no luck. Hopefully you guys can spot the error. Here's the final code that I am using.
SELECT tb2.*
FROM (SELECT `tag_table`
FROM `materials_group_tags_mapping`
WHERE `tag_id` IN
(SELECT `materials_group_tags`.`id`
FROM `materials_group_tags`
WHERE `materials_group_tags`.`name` = "frameless_base_side_material_unexposed") ) as tb2
WHERE tb2.`id` IN
(SELECT `materials_group_tags_mapping`.`tag_value`
FROM `materials_group_tags_mapping`
WHERE `materials_group_tags_mapping`.`tag_id` IN
(SELECT `materials_group_tags`.`id`
FROM `materials_group_tags`
WHERE `materials_group_tags`.`name` = "frameless_base_side_material_unexposed"))

The query gives single row query returns more than one row

I'm trying to show staff_code, staff_name and dept_name for those who have taken one book.
Here's my query:
SELECT SM.STAFF_CODE,SM.STAFF_NAME,DM.DEPT_NAME,BT.BOOK_CODE
FROM STAFF_MASTER SM,DEPARTMENT_MASTER DM,BOOK_TRANSACTIONS BT
WHERE SM.DEPT_CODE =DM.DEPT_CODE
AND SM.STAFF_CODE = (
SELECT STAFF_CODE
FROM BOOK_TRANSACTIONS
HAVING COUNT(*) > 1
GROUP BY STAFF_CODE)
It gives the error:
single-row subquery returns more than one row.
How to solve this?
Change = to IN:
WHERE SM.STAFF_CODE IN (SELECT ...)
Because the select returns multiple values, using equals won't work, but IN returns true if any of the values in a list match. The list can be a hard-coded CSV list, or a select with one column like your query is.
That will fix the error, but you also need to remove BOOK_TRANSACTIONS from the table list and remove BOOK_CODE from the select list.
After making these changes, your query would look like this:
SELECT SM.STAFF_CODE,SM.STAFF_NAME,DM.DEPT_NAME
FROM STAFF_MASTER SM,DEPARTMENT_MASTER DM
WHERE SM.DEPT_CODE =DM.DEPT_CODE
AND SM.STAFF_CODE IN (
SELECT STAFF_CODE
FROM BOOK_TRANSACTIONS
HAVING COUNT(*) > 1
GROUP BY STAFF_CODE)
I recommend learning the modern (now over 25 year old) JOIN syntax.

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.

How to show records which doesnt exist in mysql?

If I do the following query:
select * from tabla where codigo in (33,34,55,10,22,50);
msyql shows me the records that match the query.
But what if I want to know what records from this query (33,34,55,10,22,50) which are not in the database?
Is there any way to know that without having to compare one record per one by myself?
Excuse me, I din't explain it well. This shows me the records which are in the database but don't match the query. I want to know what of this records (33,34,55,10,22,50) are not in the database.
Use NOT:
select * from tabla where codigo NOT in (33,34,55,10,22,50);
UPDATE
In light of this new explanation, do this:
SELECT n.id
FROM
(SELECT 33 AS codigo
UNION SELECT 34
UNION SELECT 55
UNION SELECT 10
UNION SELECT 22
UNION SELECT 50) AS n
LEFT JOIN tabla USING (codigo)
WHERE tabla.codigo IS NULL;
Unfortunately, MySQL (and many other systems) don't give a simple way to use an arbitrary list of numbers that aren't already in some table. If you need to do this dynamically, I would suggest adding these numbers to a temp table in place of a hard-coded batch of UNIONs. Or generate a reusable numbers table (I find this fairly useful), and use the values from there. For example:
SELECT nt.id
FROM numbers_table nt
LEFT JOIN tabla ON nt.id = tabla.codigo
WHERE nt.id IN (33,34,55,10,22,50)
AND tabla.codigo IS NULL
give this a try
set #suggest_value:=10; // <---10 is the lowest value
select codigo,
#suggest_value:=#suggest_value+1,
if(codigo=#suggest_value, 0, 1) as missing_value
from tabla