SQL grouping in MySQL - mysql

Re all,
I need a little help with SQL. I got two SQL queries:
the first one counts how many occurences of a certain condition:
SELECT COUNT(*)
FROM table1
WHERE condition1 = #condition
the second one select each row that match the same condition on the same table joined with a secondary table:
SELECT *
FROM table1 INNER JOIN table2
ON table2.id = table1.id_sub
WHERE condition1 = #condition
Using both these queries in interactive fashion (by code) I can achieve the result I need but I want to optimize the procedure using SQL features instead coding.
What I really need is a query that reports just a single row for each group of rows that matches condition1.
I need also to insert the count of the matching rows as a field of the result row.
I'm running MySQL 5.6 and code the application trough Visual Studio 2013 Pro coding in C# (using MySQL.Data package).
Best Regards,
WeirdGyn

All you need to do is GROUP BY the condition1 field. It would also appear that if you just need the COUNT by group that you wouldn't need the join.
SELECT condition1, COUNT(*)
FROM table1
--INNER JOIN table2
-- ON table1.id_sub = table2.id
GROUP BY condition1

Related

SELECT multiple columns from multiple tables and don't fill blank spaces

I have what I believe to be a pretty unique use case. I would like to be able to runs a single SELECT statement on a database where I get one column from four tables. I need to run where clauses on each different table where I have one main clause that will be across each of the tables and I am not able to JOIN because the data in each column will be a different length and I don't want to have duplicate items.
I have an example of the Select statement below. Also I understand if this is not possible.
SELECT s.service_id, u.id AS "user_id", h.mac_address, l.id AS "location_id" FROM services s
LEFT JOIN db.av_product ap ON s.product_id = ap.id
WHERE s.customer_code LIKE 'test_customer'
AND u.customer_code LIKE 'test_customer'
AND h.customer_code LIKE 'test_customer'
AND l.customer_code LIKE 'test_customer'
AND s.parent_id IS NULL
AND s.active=0
AND ap.sku NOT REGEXP 'fakeregex'
AND l.active = "1"
AND h.hardware_id NOT IN ('44','45')
AND (u.support_user != 1 OR u.support_user IS NULL);
TIA!
You will need to use joins for your tables to make a single query OR you can try multiple queries merged with UNION keyword.
If you want to make a single query, have a look about SELECT DISTINCT or GROUP BY for handling duplicates.
wut up?
do you know what UNION is?
The UNION operator is used to combine the result-set of two or more SELECT statements.
but every SELECT statement within UNION must have the same number of columns; so there we got a problem.
you can handle it with WHERE operator so I won't get in to it.
anyway, UNION!
shall we?
SELECT column_name(s) FROM table1
UNION
SELECT column_name(s) FROM table2;
anyway; your solution is UNION, maybe not like what I wrote.
you can try this link too.
https://www.w3schools.com/mysql/mysql_union.asp
have a clean code

JOIN with a query that returns a query

Some SELECT statements stores in table as a field. I need to write SELECT statement that joins with some SELECT that returns SELECT.
For example:
SELECT *
FROM table1
JOIN (SELECT t_select FROM table2 WHERE = 'some_condition')
Last SELECT SELECT t_select FROM table2 returns some SELECT statement as text.
I need to join table1 with the result of the query that stores in t_select
Do I understand? Basically, you want to "evaluate" the SELECT that is stored in the table? That seems like a really poor design to me.
If you really need to do this, you'll need to pull the SELECT statement out yourself, and send it as a second query. You can't do this in pure MySQL.
Do you just want a subquery?
SELECT *
FROM table1 t1 JOIN
(SELECT t2.* FROM table2 t2 WHERE = 'some_condition') t2
on t1.<somecol> = t2.<someothercol>;
All in all you can't execute the query that is stored in the table withing another query. You will have to retrieve the query first, prepare it, and then execute it. Have a look at execute immediate :
http://dev.mysql.com/worklog/task/?id=2793
http://www.postgresql.org/docs/9.1/static/ecpg-sql-execute-immediate.html
Storing sql statements in a table is not very common, and there's usually better ways to do it.

Nested SELECT SQL Queries Workbench

Hi i have this query but its giving me an error of Operand should contain 1 column(s) not sure why?
Select *,
(Select *
FROM InstrumentModel
WHERE InstrumentModel.InstrumentModelID=Instrument.InstrumentModelID)
FROM Instrument
according to your query you wanted to get data from instrument and instrumentModel table and in your case its expecting "from table name " after your select * .when the subselect query runs to get its result its not finding table instrument.InstrumentModelId inorder to fetch result from both the table by matching you can use join .or you can also select perticuler fields by tableName.fieldName and in where condition use your condition.
like :
select Instrument.x,InstrumentModel.y
from instrument,instrumentModel
where instrument.x=instrumentModel.y
You can use a join to select from 2 connected tables
select *
from Instrument i
join InstrumentModel m on m.InstrumentModelID = i.InstrumentModelID
When you use subqueries in the column list, they need to return exactly one value. You can read more in the documentation
as a user commented in the documentation, using subqueries like this can ruin your performance:
when the same subquery is used several times, mysql does not use this fact to optimize the query, so be careful not to run into performance problems.
example:
SELECT
col0,
(SELECT col1 FROM table1 WHERE table1.id = table0.id),
(SELECT col2 FROM table1 WHERE table1.id = table0.id)
FROM
table0
WHERE ...
the join of table0 with table1 is executed once for EACH subquery, leading to very bad performance for this kind of query.
Therefore you should rather join the tables, as described by the other answer.

match multiple columns to multiple-row subquery?

I'm very much still learning about mySQL (am still really only comfortable with basic queries, count, order by etc.). It is very likely that this question has been asked before, however either I don't know what to search for, or I'm too much of a novice to understand the answers:
I have two tables:
tb1 (a,b,path)
tb2 (a,b,value)
I would like to make a query that returns "path" for each row in tb1 whose a,b matches a different query on tb2. In bad mysql, it would be something like:
select
path
from tb1
where
a=(select a from tb2 where value < v1)
and
b=(select b from tb2 where value < v1);
however, this doesn't work, as the subqueries are returning multiple values. Note that exchanging = by in is not good enough, as that would be true for combinations of a,b-values that are not returned by select a,b from tb2 where value < v1
Basically, I have identified an interesting area in (a,b)-space based on tb2, and would like to study the behavior of tb1 within that area (if that makes it any clearer).
thank you :)
This is a job for an INNER JOIN on both a and b:
SELECT
path
FROM
tb1
INNER JOIN tb2 ON tb1.a = tb2.a AND tb1.b = tb2.b
/* add your condition to the WHERE clause */
WHERE tb2.value < v1
The use cases for subqueries in the SELECT list or WHERE clause can very often be handled instead using some type of JOIN. The join will frequently be faster than the subquery, owing to the fact that when using a SELECT or WHERE subquery, the subquery may need to be performed for each row returned, rather than only once.
Beyond the MySQL documentation on JOINs linked above, I would also recommend Jeff Atwood's Visual Explanation of SQL JOINs
INNER JOIN will do the trick.
You just need two ON criteria in order to match both the a and b values, like so:
SELECT path
FROM tb1
INNER JOIN tb2 ON tb1.a = tb2.a AND tb1.b = tb2.b
WHERE tb2.value < v1
You can limit your result set this way:
select
path
from tb1
where
a=(select a from tb2 where value < v1 LIMIT 1)
and
b=(select b from tb2 where value < v1 LIMIT 1);

Loops in MySQL alone

I'd like to select from one table and use the results of that select to update another table, but only based on certain conditions. Is this possible with a 1-time SQL query?
Yes it is.
UPDATE
tableToUpdate AS ttu
[LEFT|RIGHT|INNER] JOIN
otherTable AS ot
ON
joinCondition
SET
ttu.field = ot.field
WHERE
conditionsToBeMet
AS otherTable you can just use the SELECT query that you use to fetch your resultset.