I have the following query
SELECT *
FROM(
(SELECT
MAX(c.start_time) as start_1
FROM
c1 c)
UNION ALL
(SELECT
MAX(cc.created_at) as ccmax
FROM
cc1)
) as t
I'd like to have the result in a table with 2 columns start_1 and cmax instead of the single column I get with all the different results listed.
How should I do it? I ended up in a subselect believing this would have done the job.
For the data to be in two columns you would have to use a sub select.
SELECT
MAX(c1.start_time) as start_1, (SELECT MAX(cc1.created_at) FROM cc1) as ccmax
FROM c1
I want to extract some information from two different table in one database,
[(first table): id-nbrNight-........]
[(second table): id-........]
I want to extract the nbrNight from the first table & the id from the second table:
so in my case I write this, but I don't know how to rassemble this two line in one line:
SELECT sum(nbrNight) as night FROM firsttab
SELECT count(`id`) as id FROM secondtab
I wirte this to rassemble this two line:
SELECT sum(nbrNight) as night,count(`id`) FROM firsttab,secondtab
But it doesn't work!
You can use UNION to combine the result from two query like
SELECT sum(nbrNight) as night FROM firsttab
UNION
SELECT count(`id`) as id FROM secondtab
(OR) do a JOIN with both tables using a common column between them (if any present) like below (assuming id is the common column between them)
SELECT sum(t1.nbrNight) as nightsum, count(t2.`id`) as idcount
FROM firsttab t1 JOIN secondtab t2 ON t1.id = t2.id
One option is to use the queries as inline views; reference those queries as a rowsource (like a table) in another query.
Since each query returns a single row, you can safely perform a JOIN operation, without need for any join predicate (aka CROSS JOIN).
For example:
SELECT f.night
, s.id
FROM ( SELECT SUM(nbrNight) AS night FROM firsttab ) f
CROSS
JOIN ( SELECT COUNT(id) AS id FROM secondtab ) s
Another option (since both queries are guaranteed to return exactly one row, if they don't return an error) is to include the query in the SELECT list of another query. It's not necessary to include a column alias in the subquery, but we can assign an alias.
For example:
SELECT ( SELECT SUM(nbrNight) FROM firsttab ) AS night
, ( SELECT COUNT(id) FROM secondtab ) AS id
If either of the queries were returning more than one column, then the approach in the first example will still work. The inline view queries can return multiple expressions, and we can reference those expressions in the outer query. With the pattern in the second example, that imposes a restriction that the subqueries must return only one expression (one column).
As an example to demonstrate an inline view returning more than one column, the inline view f returns three expressions:
SELECT f.night
, f.cnt
, f.min_nbr
, s.id
FROM ( SELECT SUM(nbrNight) AS night
, COUNT(nbrNight) AS cnt
, MIN(nbrNight) AS min_nbr
FROM firsttab
) f
CROSS
JOIN ( SELECT COUNT(id) AS id FROM secondtab ) s
I have a table with duplicate skus.
skua
skua
skub
skub
skub
skuc
skuc
skud
SELECT sku, COUNT(1) AS `Count` FROM products GROUP BY sku;
shows me all the skus that have duplicates and the number of duplicates
skua 2
skub 3
skuc 2
skud 1
I am trying to find how many there are with 2 duplicates, 3 duplicates etc.
i.e.
duplicated count
1 1 (skud)
2 2 (skua, and skuc)
3 1 (skub)
and I don't know how to write the sql. I imagine it needs a subselect...
thanks
Just use your current query as an inline view, and use the rows from that just like it was from a table.
e.g.
SELECT t.Count AS `duplicated`
, COUNT(1) AS `count`
FROM ( SELECT sku, COUNT(1) AS `Count` FROM products GROUP BY sku ) t
GROUP BY t.Count
MySQL refers to an inline view as a "derived table", and that name makes sense, when we understand how MySQL actually processes that. MySQL runs that inner query, and creates a temporary MyISAM table; once that is done, MySQL runs the outer query, using the temporary MyISAM table. (You'll see that if you run an EXPLAIN on the query.)
Above, I left your query just as you formatted it; I'd tend to reformat your query, so that entire query looks like this:
SELECT t.Count AS `duplicated'
, COUNT(1) AS `count`
FROM ( SELECT p.sku
, COUNT(1) AS `Count`
FROM products p
GROUP BY p.sku
) t
GROUP BY t.Count
(Just makes it easier for me to see the inner query, and easier to extract it and run it separately. And qualifying all column references (with a table alias or table name) is a best practice.)
select dup_count as duplicated,
count(*) as `count`,
group_concat(sku) as skus
from
(
SELECT sku, COUNT(1) AS dup_count
FROM products
GROUP BY sku
) tmp_tbl
group by dup_count
I have a list of ids and need to check whether user with id is in DB or not in one SELECT. Like SELECT WHERE IN (). But SELECT WHERE IN () doesn't suit my needs, I need in one SELECT distinguish those ids that are in table, and those that are not, not using any loops like multiple SELECTS. Any ideas are welcome!
I'm not sure if this is what you need, but I guess you have table 1 which contains a lot of IDs, and you would like to see which ones occur in table 2 and which ones don't?
select T1.ID, count(*) 'Times of occurrences in T2'
from table 1 T1
left outer join table 2 T2
ON T1.ID = T2.ID
group by T1.ID
You should provide more details. Would it be a single query so a list could be hardcoded into query or you want to find general solution for any list of ids provided? How long is your list?
For single query and not very long list you can use union. On example:
SELECT some_value, EXISTS( SELECT 1 FROM tableName WHERE user_id = some_value )
UNION ALL
SELECT other_value, EXISTS( SELECT 1 FROM tableName WHERE user_id = other_value )
UNION ALL
SELECT other_value2, EXISTS( SELECT 1 FROM tableName WHERE user_id = other_value2 )
UNION ALL
.....
If your list of ids can vary and/or consists of thousands of records it is impossible. In list you have columnar layout and you want to change it to row-level results. In MsSQL there are PIVOT, UNPIVOT clauses which can do that. In MySQL such transformation without explicit unions are impossible.
What is the easiest way to select data from two tables and rather than join them, have them appear as separate rows. Both tables have similar or matching fields and I want to run some aggregate function on them such as avg all the rows that occurred in the same month, from both tables.
for example I have two tables, one that is shows transactions from one system and another with transactions from a different system. Is there a way to grab all the transactions from both tables as separate rows? if table 1 had twenty records and table 2 have thirty records, I'd like there to be 50 rows on the return.
You could try something like this:
SELECT ...
FROM (
SELECT f1,f2,f3 FROM table1
UNION
SELECT f1,f2,f3 FROM table2
)
WHERE ...
You could try this notattion:
SELECT * from table1,table2
More complicated one :
SELECT table1.field1,table1.field2, table2.field3,table2.field8 from table1,table2 where table1.field2 = something and table2.field3 = somethingelse
Such queries are usually called "implicit JOINs" and Explicit vs implicit SQL joins asks how both compare. In some cases implicit query execution planning is identical to explicit JOINs.
The UNION ALL operator may be what you are looking for.
With this operator, you can concatenate the resultsets from multiple queries together, preserving all of the rows from each. Note that a UNION operator (without the ALL keyword) will eliminate any "duplicate" rows which exist in the resultset. The UNION ALL operator preserves all of the rows from each query (and will likely perform better since it doesn't have the overhead of performing the duplicate check and removal operation).
The number of columns and data type of each column must match in each of the queries. If one of the queries has more columns than the other, we sometimes include dummy expressions in the other query to make the columns and datatypes "match". Often, it's helpful to include an expression (an extra column) in the SELECT list of each query that returns a literal, to reveal which of the queries was the "source" of the row.
SELECT 'q1' AS source, a, b, c, d FROM t1 WHERE ...
UNION ALL
SELECT 'q2', t2.fee, t2.fi, t2.fo, 'fum' FROM t2 JOIN t3 ON ...
UNION ALL
SELECT 'q3', '1', '2', buckle, my_shoe FROM t4
You can wrap a query like this in a set of parenthesis, and use it as an inline view (or "derived table", in MySQL lingo), so that you can perform aggregate operations on all of the rows.
SELECT t.a
, SUM(t.b)
, AVG(t.c)
FROM (
SELECT 'q1' AS source, a, b, c, d FROM t1
UNION ALL
SELECT 'q2', t2.fee, t2.fi, t2.fo, 'fum' FROM t2
) t
GROUP BY t.a
ORDER BY t.a
If your question was this -- Select ename, dname FROM emp, dept without using joins..
Then, I would do this...
SELECT ename, (SELECT dname
FROM dept
WHERE dept.deptno=emp.deptno)dname
FROM EMP
Output:
ENAME DNAME
---------- --------------
SMITH RESEARCH
ALLEN SALES
WARD SALES
JONES RESEARCH
MARTIN SALES
BLAKE SALES
CLARK ACCOUNTING
SCOTT RESEARCH
KING ACCOUNTING
TURNER SALES
ADAMS RESEARCH
ENAME DNAME
---------- --------------
JAMES SALES
FORD RESEARCH
MILLER ACCOUNTING
14 rows selected.
You should try this
SELECT t1.*,t2.* FROM t1,t2
SELECT * from table1
UNION
SELECT * FROM table2
Union will fetch data by row not column,So If your are like me who is looking for fetching column data from two different table with no relation and without join.
In my case I am fetching state name and country name by id. Instead of writing two query you can do this way.
select
(
select s.state_name from state s where s.state_id=3
) statename,
(
select c.description from country c where c.id=5
) countryname
from dual;
where dual is a dummy table with single column--anything just require table to view
select 'test', (select name from employee where id=1) as name, (select name from address where id=2) as address ;
In this case we are assuming that we have two tables:
SMPPMsgLogand SMSService with common column serviceid:
SELECT sp.SMS,ss.CMD
FROM vas.SMPPMsgLog AS sp,vas.SMSService AS ss
WHERE sp.serviceid=5431
AND ss.ServiceID = 5431
AND Receiver ="232700000"
AND date(TimeStamp) <='2013-08-07'
AND date(TimeStamp) >='2013-08-06' \G;
you can try this works always for me
query="SELECT * from tableX,tableY,table8";