Subquery invalid result with MySQL - mysql

I've an issue with the columns result from a subquery.
When I write the query:
select Q1.numi, Q1.sir from (select numi, sir from cust_vehicle where topg = 'VU') Q1
inner join (select id_contact, sir, ni from cust_contact) Q2 on Q1.sir = Q2.sir
I get 2 output columns (numi and sir).
But if I transform the query above as a subquery like:
select Q3.*
from (
select Q1.numi, Q1.sir from (select numi, sir from cust_vehicle where topg = 'VU') Q1
inner join (select id_contact, sir, ni from cust_contact) Q2 on Q1.sir = Q2.sir
) Q3
I get only the first column as output (the numi field).
Why do I have this behaviour?
For information, I use MySQL 5.6.11 on OS X 10.8

I found the origin of the problem. It's MySQL Workbench.
I opened a new SQL sheet and pasted my query in it. Now, all work fine.
Thanks for your help :)

SELECT cv.numi
, cv.sir
, cc.id_contact
, cc.ni
FROM cust_vehicle cv
JOIN cust_contact cc
ON cc.sir = cv.sir
WHERE cv.topg = 'VU'

Related

SQL Query Count With JOIN

I've the following SQL Query which runs perfectly fine but now i want to calculate the count based on the following scenario:
SELECT d.vseverity, v.vulnstatus, v.vtitleid, d.vtitle
FROM vulnsummary v
JOIN project p ON v.projid = p.projid
AND v.stagename = p.currentstage
JOIN datasets d ON v.vtitleid = d.datasetid
The current Output is:
Now i want to show the count like this way:
High (Open) - 2
High (Closed) - 0
Medium (Open) - 1
Medium (Closed) - 0
Low (Open) - 3
Low (Closed) - 1
Please help me to solve this query, Thank You
You need to CROSS JOIN the distinct sets of severity and status values and then LEFT JOIN that to your table to allow you to count the values of each severity/status combination. Without sample data it's hard to be certain but something like this should work:
SELECT sv.vseverity, st.vulnstatus, COUNT(v.vseverity) AS count
FROM (
SELECT DISTINCT vseverity
FROM datasets
) sv
CROSS JOIN (
SELECT DISTINCT vulnstatus
FROM vulnsummary
) st
LEFT JOIN (
SELECT d.vseverity, v.vulnstatus
FROM vulnsummary v
JOIN project p ON v.projid = p.projid
AND v.stagename = p.currentstage
JOIN datasets d ON v.vtitleid = d.datasetid
) v ON v.vseverity = sv.vseverity AND v.vulnstatus = st.vulnstatus
GROUP BY sv.vseverity, st.vulnstatus
I don't have your full dataset, however, a RIGHT OUTER JOIN to a master volnstatus table will enable (the volnstatus table showing all options i.e. 'Open', 'Closed'). A rough draft example, with only the volnstatus table populated:
SELECT COUNT(s.vulnstatus) CountOf, t.vtype
FROM dbo.vusummary s
RIGHT OUTER JOIN
vusummarytype t
ON s.vulnstatus = t.vtype
GROUP BY t.vtype

how to optimize mysql query with inner join

select id from customer_details where store_client_id = 2
And
id NOT IN (select customer_detail_id from orders
where store_client_id = 2 and total_spent > 100 GROUP BY customer_detail_id )
Or
id IN (select tcd.id from property_details as pd, customer_details as tcd
where pd.store_client_id = 2 and pd.customer_detail_id = tcd.customer_id and pd.property_key = 'Accepts Marketing'
and pd.property_value = 'no')
And
id IN (select customer_detail_id from orders
where store_client_id = 2 GROUP BY customer_detail_id HAVING count(customer_detail_id) > 0 )
Or
id IN (select tor.customer_detail_id from ordered_products as top, orders as tor
where tor.id = top.order_id and tor.store_client_id = 2
GROUP BY tor.customer_detail_id having sum(top.price) = 1)`
I have this mysql query with inner join so when it run in mysql server it slow down what is the issue cant find.
But after 4-5 minutes it return 15 000 records. This records is not an issue may be.
In some tutorial suggest to use Inner join, Left join,...
But I don't know how to convert this query in Join clause.
Any help will be appreciated. Thanks in advance.
First of all please read relational model and optimizing select statements.

`Convert mySQL Query to SQLite Using SUM and GROUP BY

I am working on a mobile app that is currently using an ajax call to run a mySQL query remotely and return the data as an array. I want to run the query locally using SQLite 3 an iPad. Below is the mySQL query. I am having trouble getting the query to work in SQLite
This is my working mySQL Query
SELECT
expense_date.expenseDate,
expenses.cost,
SUM(expenses.cost) as total,
expenses.name,
category.category
FROM expenses
INNER JOIN category ON expenses.catID = category.catID
INNER JOIN expense_date ON expenses.dateID = expense_date.dateID
WHERE expense_date.expenseDate BETWEEN '#from#' AND '#tu#'
AND expenses.catID != '1F27C7A1-3E16-5087-A313-A47D286A77A5'
AND expenses.catID != 'DF64C183-5056-A816-1ACA94F902242B61'
AND expenses.userID = '#userID#'
AND expenses.accountID = '#accountID#'
Group By expense_date.expenseDate
UPDATED MySQL Statement. This statement works in mySQL but not in SQLite 3.
SELECT
expense_date.expenseDate,
SUM(expenses.cost) as total
FROM expenses
INNER JOIN expense_date ON expenses.dateID = expense_date.dateID
WHERE expense_date.expenseDate
BETWEEN '2014-08-01' AND '2014-08-31'
AND expenses.catID != '1F27C7A1-3E16-5087-A313-A47D286A77A5'
AND expenses.catID != 'DF64C183-5056-A816-1ACA94F902242B61'
AND expenses.userID = 'C4C73329-5056-A816-1AB4B9FAE08FDB77'
AND expenses.accountID = '46298719-C78A-4CCE-8ADD-A3FD948DF93E'
Group By expense_date.expenseDate
This is the results of the query. 2014-08-21 has two values for that date: 2000.00 and 372.00 but they are added together and returned as a single value for 2014-08-21.
2014-08-01 32.00
2014-08-16 15.00
2014-08-19 513.55
2014-08-21 2372.00
2014-08-22 525.00
2014-08-25 34.55
2014-08-27 52.78
2014-08-31 30.00
I need to convert the MySQL query code to SQLite. I did a google search and found some info about using CASE but I am not sure how to construct the sql statement. Your help is appreciated
Your SQL query actually doesn't make sense in MySQL, because several of the selected values are indeterminate. You might try something like this:
SELECT ed.expenseDate, SUM(e.cost) as total,
group_concat(e.name) as names,
group_concat(c.category) as categories
FROM expenses e INNER JOIN
category c
ON e.catID = e.catID INNER JOIN
expense_date ed
ON e.dateID = ed.dateID
WHERE ed.expenseDate BETWEEN '#from#' AND '#tu#' AND
e.catID <> '1F27C7A1-3E16-5087-A313-A47D286A77A5' AND
e.catID <> 'DF64C183-5056-A816-1ACA94F902242B61' AND
e.userID = '#userID#' AND
e.accountID = '#accountID#'
Group By ed.expenseDate;
This is the SQLite sql statement that solved my problem.
SELECT expense_date.expenseDate,
SUM(expenses.cost) AS total
FROM expenses INNER JOIN expense_date ON expenses.dateID = expense_date.dateID
WHERE expense_date.expenseDate BETWEEN '"+from+"' AND '"+tu+"'
AND expenses.catID <> '1F27C7A1-3E16-5087-A313-A47D286A77A5'
AND expenses.catID <> 'DF64C183-5056-A816-1ACA94F902242B61' Group By expense_date.expenseDate
Thanks for everyones help.

Subscribe between fields In sql

i have a table with these fields
id,cid,cv
with these data
1,5,code
2,3,code4
3,3,cod2
1,4,code5
1,3,code4
] want select id what cid=5 and cv=code and cid=3 or 4 and cv=code4.
I expect that id=1.
I used this query,but result is 0
SELECT id FROM table WHERE (cid='5' and cv='code') and (cid in ('3','4') and cv='code4')
sorry for bad english.
SELECT id FROM my_table
WHERE (cid=5 and cv='code')
or ((cid = 3 and cv='code4')
and (cid = 4 and cv='code4'))
group by id
SQL Fiddle Example
Try this (change the AND between the parenteses to OR):
SELECT id
FROM table
WHERE (cid='5' and cv='code') OR (cid in ('3','4') and cv='code4')
You should try using ORs instead of ANDs
SELECT id
FROM table
WHERE (cid='5' and cv='code')
OR (cid in ('3','4') and cv='code4')
I put this at http://sqlfiddle.com/#!2/40054/51 (you can tell by the last number being 51 I took some wrong turns). I think this is called "Key Value," I proposed an edit to the tags for this post, but I think you should re-tag it to include key-value. Anyway: databases like this are difficult to query compared to approaches where one row refers to one thing - instead you have one row referring to one attribute. So if you want to know something about what "things" have certain attributes, you have to paste the attributes for each thing together in one row. Run the query below and you'll see what I mean:
SELECT laptops.laptop, rams.termvalue as ramCount,
cpus.termvalue as cpusCount,
maker.termvalue as company
FROM (SELECT DISTINCT laptop FROM my_table) As Laptops
LEFT JOIN (SELECT laptop, termvalue FROM my_table
WHERE term = 'ram') AS rams
ON rams.laptop = laptops.laptop
LEFT JOIN (SELECT laptop, termvalue FROM my_table
WHERE term = 'cpu') AS cpus
ON cpus.laptop = laptops.laptop
LEFT JOIN (SELECT laptop, termvalue FROM my_table
WHERE term = 'company') AS maker
ON maker.laptop = laptops.laptop
If you put up other questions about this type of database, you should always mention that you're using a "key/value" arrangement, it's uncommon and not what any of us assumed.
In your fiddler example you wanted to find company = dell and cpu = 2 or ram = 2, so you would query that whole query by wrapping it in parentheses and giving it an alias, like this:
SELECT * FROM (
SELECT laptops.laptop, rams.termvalue as ramCount,
cpus.termvalue as cpusCount,
maker.termvalue as company
FROM (SELECT DISTINCT laptop FROM my_table) As Laptops
LEFT JOIN (SELECT laptop, termvalue FROM my_table
WHERE term = 'ram') AS rams
ON rams.laptop = laptops.laptop
LEFT JOIN (SELECT laptop, termvalue FROM my_table
WHERE term = 'cpu') AS cpus
ON cpus.laptop = laptops.laptop
LEFT JOIN (SELECT laptop, termvalue FROM my_table
WHERE term = 'company') AS maker
ON maker.laptop = laptops.laptop
) as laps
WHERE company = 'dell' AND (cpuscount = 2 OR ramcount = 2)

MS Access - Aggregate functions and max

I have this query, where I am trying to get max age of a retail store seller(There's multiple towns), and show multiple if there's multiple people with the same (max)age. I am using Microsoft Access 2010. Here is the query:
SELECT Linnad.Linn, Myyjad.Nimi, Max(Myyjad.Vanus) As Vanus
FROM Linnad INNER JOIN Myyjad ON Linnad.LinnID = Myyjad.LinnID
GROUP BY Linnad.Linn, Myyjad.Nimi
ORDER BY Linnad.Linn;
The problem is, it seems to ignore the MAX, and just shows all of the values, and I can't remove the group by Myyjad.Nimi, because it gives me an error that aggregate function not included for Myyjad.Nimi.
And the output should be:
Town - Name - Max(Age)
Also, Linn = Town, Nimi = Name and the Vanus = Age.
I think this may be what your looking for:
SELECT L.Linn, M.Nimi, M.Vanus
FROM Linnad As L,
(
SELECT M2.LinnID, M2.Nimi, M2.Vanus
FROM Myyjad As M2
WHERE M2.Vanus = (SELECT Max(Z.Vanus) FROM Myyjad As Z WHERE Z.LinnID = M2.LinnID)
) As M
WHERE M.LinnID = L.LinnID
This performs a sub-select to get a list of the Linn ID's with all Nimi's showing the maximum Vanus, then we link this sub-select back to the Linnad table via the LinnID.
I think you want:
SELECT Linnad.Linn, Myyjad.Nimi, Myyjad.Vanus
FROM Linnad INNER JOIN Myyjad ON Linnad.LinnID = Myyjad.LinnID
WHERE DateValue(Myyjad.Vanus)
= (SELECT Max(DateValue(Myyjad.Vanus)) FROM Myyjad)
ORDER BY Linnad.Linn
Top N per group:
SELECT Linnad.Linn, Myyjad.Nimi, Myyjad.Vanus
FROM FROM Linnad INNER JOIN Myyjad ON Linnad.LinnID = Myyjad.LinnID
WHERE Myyjad.ID In (
SELECT Top 1 m.ID
FROM Myyjad m
WHERE m.LinnID=Linnad.ID
ORDER BY m.Vanus Desc, m.ID)
Grouping by Linn (town) and Nimi (name) tells the db engine to give you one row for each combination of town and name, and show you the maximum Vanus (age) for each of those combinations. And logically, that's not what you want. You want the name of each person whose age is the same as the maximum age in that town.
First verify you can retrieve the max age for each LinnID.
SELECT
LinnID,
Max(Vanus) As MaxOfVanus
FROM
Myyjad
GROUP BY LinnID;
If that works, you can save it as "qryTownAge", then use it in another query where you join it (on LinnID) with Linnad. That will allow you to retrieve the matching Linn.
SELECT l.LinnID, l.Linn, q.MaxOfVanus
FROM
Linnad AS l
INNER JOIN qryTownAge AS q
ON l.LinnID = q.LinnID
ORDER BY l.Linn;
If that works, save it as qryTownAge2. Then try this query.
SELECT q.Linn, q.MaxOfVanus, m.Nimi
FROM
qryTownAge2 AS q
INNER JOIN Myyjad AS m
ON (
m.LinnID = q.LinnID
AND m.Vanus = q.MaxOfVanus
)
ORDER BY q.Linn;
If that all works, you could create a single query which does it all. However, doing it step by step should help us pinpoint errors.