Combining two mysql queries - php

I have two sql queries...
set #count:=0;
select #count:=#count+1 as SNO, col1, col2 FROM table;
I want to combine above queries into a single query. Any Help?

You can simply do this,
select #count:=#count+1 as SNO, col1, col2
FROM table, (SELECT #count:=0) r ;
Just like adding RowNumber for each row
select #rownum:=#rownum+1 ‘rank’,
p.*
from player p, (SELECT #rownum:=0) r
order by score
desc limit 10;
Adding RowNumber in MySQL

As per my understanding,you are looking for Row_Number function in this case. If this is correct, please have a look here
e.g.
Select #count := #count + 1 As SNO, col1, col2
From table ,(SELECT #count:=0) foo
may help
Also you can refer ROW_NUMBER, Partition, and Over in MySQL for more understanding on the same

Combining two queries..
SELECT t1.field1, t1.field2, t2.field1
FROM (query1) as t1, (query2) as t2
WHERE t1.field1= t2.field1
Hope this will works ...

select #count:=#count+1 as SNO, col1, col2 FROM table, (SELECT #count:=0) t;

Related

ORDER BY RAND() for multiple columns (shuffle content of each column vertically)

I'm looking for a mysql solution to have several columns output a random field from that column.
The query I have now only selects the entire row randomly but does not randomize the separated columns.
$sql = "SELECT col1, col2, col3, col4 FROM table ORDER BY RAND() limit 4";
I tried subqueries but I'm not familiar with that so if anyone could help ...
Try this:
SELECT CASE rnd
WHEN 1 THEN col1
WHEN 2 THEN col2
WHEN 3 THEN col3
WHEN 4 THEN col4
END AS col
FROM (
SELECT col1, col2, col3, col4,
FLOOR(RAND() * 4) + 1 AS rnd
FROM mytable
ORDER BY RAND() ) AS t
Expression FLOOR(RAND() * 4) + 1 generates a random number between 1 and 4 (inclusive). The outer query uses this number to randomly pick one of the 4 columns of the table.
Demo here
Edit:
If you want to shuffle columns the you can use the following query:
SELECT CASE FIND_IN_SET(1, rnd)
WHEN 1 THEN col1
WHEN 2 THEN col2
WHEN 3 THEN col3
WHEN 4 THEN col4
END AS c1,
CASE FIND_IN_SET(2, rnd)
WHEN 1 THEN col1
WHEN 2 THEN col2
WHEN 3 THEN col3
WHEN 4 THEN col4
END AS c2,
CASE FIND_IN_SET(3, rnd)
WHEN 1 THEN col1
WHEN 2 THEN col2
WHEN 3 THEN col3
WHEN 4 THEN col4
END AS c3,
CASE FIND_IN_SET(4, rnd)
WHEN 1 THEN col1
WHEN 2 THEN col2
WHEN 3 THEN col3
WHEN 4 THEN col4
END AS c4
FROM (
SELECT col1, col2, col3, col4,
(SELECT GROUP_CONCAT(i ORDER BY RAND())
FROM (SELECT 1 AS i UNION ALL SELECT 2 UNION ALL
SELECT 3 UNION ALL SELECT 4) t) AS rnd
FROM mytable) AS t
Demo here
If every resulting row has to be independent then there is no other way than to select 16 random rows (once for each cell in your 4x4 resulting table).
SELECT
(SELECT col1 FROM `table` ORDER BY RAND() LIMIT 1) AS col1,
(SELECT col2 FROM `table` ORDER BY RAND() LIMIT 1) AS col2,
(SELECT col3 FROM `table` ORDER BY RAND() LIMIT 1) AS col3,
(SELECT col4 FROM `table` ORDER BY RAND() LIMIT 1) AS col4
FROM `table`
LIMIT 4
I think it'd be simpler if you randomize the columns in PHP as well but as a fun challenge I thought I would do it like below.
It'll give you random 4 rows and randomize/shuffle the column values.
Fist it simply GROUP_CONCAT values 1,2,3,4 but randomize the order ..then extract the indexes of numbers using FIND_IN_SET..then selects the col values based on these indexes using ELT() function.
SELECT
ELT(FIND_IN_SET(1,rand_indexes),col1,col2,col3,col4) as col1,
ELT(FIND_IN_SET(2,rand_indexes),col1,col2,col3,col4) as col2,
ELT(FIND_IN_SET(3,rand_indexes),col1,col2,col3,col4) as col3,
ELT(FIND_IN_SET(4,rand_indexes),col1,col2,col3,col4) as col4
FROM
(SELECT col1,col2,col3,col4,
(SELECT GROUP_CONCAT(i ORDER BY RAND()) as indexes FROM
(SELECT 1 as i UNION SELECT 2 UNION SELECT 3 UNION SELECT 4)indexes
)as rand_indexes
FROM `table`
)T1
ORDER BY RAND() limit 4
sqlfiddle
UPDATE If you want to shuffle your column vertically like you have mentioned in comment, then you can use this query it.
It basically selects first column 4 rows in random order then joins with 4 random rows of second column and so on...
SELECT T1.col1,T2.col2,T3.col3,T4.col4
FROM
(SELECT col1,#order1:=#order1+1 as i
FROM (SELECT col1 FROM `table` ORDER BY RAND() LIMIT 4) O1,(SELECT #order1:=0) initialize )T1
INNER JOIN
(SELECT col2,#order2:=#order2+1 as i
FROM (SELECT col2 FROM `table` ORDER BY RAND() LIMIT 4) O1,(SELECT #order2:=0) initialize )T2
ON T1.i = T2.i
INNER JOIN
(SELECT col3,#order3:=#order3+1 as i
FROM (SELECT col3 FROM `table` ORDER BY RAND() LIMIT 4) O1,(SELECT #order3:=0) initialize )T3
ON T1.i = T3.i
INNER JOIN
(SELECT col4,#order4:=#order4+1 as i
FROM (SELECT col4 FROM `table` ORDER BY RAND() LIMIT 4) O1,(SELECT #order4:=0) initialize )T4
ON T1.i = T4.i
sqlfiddle shuffle columns vertically
This one will do but I guess I'm sure it's not performing very good:
select * from
(select col1 from table order by rand()) as a,
(select col2 from table order by rand()) as b,
(select col3 from table order by rand()) as c,
(select col4 from table order by rand()) as d
order by rand()
limit 4;
It does a cross join on all 4 tables (giving n^4 rows) and then fetches the first 4 rows of that.
Update because the OP asked about the purpose of a/b/c/d:
The a, b, etc. are just (randomly chosen) aliases for the 4 subqueries and can be seen as (temporary) table names.
They are required for the syntax to refer to the subqueries. In this particular example they are useless, but MySQL (and probably other systems as well) needs them.
In the above statement the column names are already unique, but consider the case when column names are not uniqe and you wanted to perform some operations on the columns, like so:
select concat(a.col1, ' ', c.col1), b.col2, d.col2 from
(select col1 from table order by rand()) as a,
(select col2 from table order by rand()) as b,
(select col1 from table order by rand()) as c,
(select col2 from table order by rand()) as d
where b.col2 > d.col2
order by rand()
limit 4;
Then these aliases a to d are really needed to distinguish e.g. col1 from the 1st and 3rd subselect.
However, #PaulSpiegel's answer is better than mine because I missed the limit 1 in the subqueries.

How to get row number in select query

i try this query to get row number in selected rows, but the output comes like 23,56,78,.... i need to get 1,2,3 to every selected row. please help me
SET #row=0;
SELECT `table1`.`col1`,`table1`.`col2`,#row:=#row+1
FROM `table1`
LEFT OUTER JOIN `table2` ON `table1`.`col1` = `table2`.`col5`
WHERE `table2`.`col5` IS NOT NULL
GROUP BY `col1` ORDER BY `table1`.`col7` DESC LIMIT 0,10
Move the query with the ORDER BY clause into a subquery.
SET #row = 0;
SELECT col1, col2, #row := #row+1
FROM (SELECT table1.col1, table1.col2
FROM table1
LEFT JOIN table2 ON table1.col1 = table2.col5
WHERE table2.col5 IS NOT NULL
GROUP BY col1
ORDER BY table1.col7 DESC
LIMIT 0, 10) AS subquery
You can try using an inline view. Use a query that gets the rows you want to return, and then wrap that in parens, and reference that query in the FROM clause of an outer query.
Something like this:
SELECT v.`col1`
, v.`col2`
, #row := #row + 1 AS `rn`
FROM ( SELECT `table1`.`col1`
, `table1`.`col2`
FROM `table1`
...
ORDER BY ...
LIMIT 10
) v

To get count of a row with particular condition

I want to get count of a row it exists in table.
+---+----+
|id |name|
+---+----+
|100|a |
+---+----+
|201|b |
+---+----+
|302|c |
+---+----+
|403|d |
+---+----+
|504|e |
+---+----+
In the above table i want to get output as 4(i.e) the count of that row exists. I have 'd' value and have to write a query to get the output as 4 where name = d
I think code will be something like the below,
select count(*) ......
If i'm correctly understand you this query is what you want:
set #row_number = 0;
select #row_number := #row_number + 1 as row_number,name FROM table_name;
SELECT ROW_NUMBER() OVER(ORDER BY id) FROM yourtable WHERE name='d'
MySQL version
SET #rank=0;
SELECT #rank := #rank+1 AS rank
FROM yourtable WHERE name='d'
ORDER BY id asc
#vinoth I think #Pragmatist Answer would work for you. Just add this clause to his query :
set #row_number = 0;
select #row_number := #row_number + 1 as row_number,name FROM table_name Where name='b';
Try the below. MS SQL is a tested query, i just converted into mysql. Hope you can modify as per your requirement.
SET #rank=0;
SELECT * FROM Table1 T1
INNER JOIN(
SELECT #rank := #rank+1 AS rank, ID
FROM Table1
ORDER BY id asc) temp ON temp.ID = T1.ID
WHERE T1.name = 'd'
MS SQL Query will be
SELECT * FROM Table1 T1
INNER JOIN(SELECT id, ROW_NUMBER() OVER (Order by id) AS RowNumber from Table1) temp ON temp.ID = T1.ID
WHERE T1.name = 'd'
To get the Row Number
SELECT ROW_NUMBER() OVER(ORDER BY id) from table WHERE name='d'
To get the row count with your condition use below query
select count(*) as count from table where name = 'b'

How to know the table name inside a fetch_array

I am doing a query with union from two different tables and then on the fetch_array loop I would like to know from which table out of the two I am actually grabbing, anyway without adding a flag into the table's structures. ?
The flag doesn't need to be in the table, but can easily be in the query:
SELECT 'table1' as t, ... FROM table1
UNION
SELECT 'table2' as t, ... FROM table2
...
echo $row['t'];
You don't have to select fields from a table, you can simply "select a string literal" too.
If you have columns with identical name in both tables you could use as
SELECT table1.col1 as col1, table1.col2, table1.col3 FROM table1
UNION
SELECT table2.col1 as col4, table1.col5 FROM table2
then when you do $data = fetch_assoc($q) you will have
$data["col1"] // table1.col1
$data["col2"] // table1.col2
-----------------------------
$data["col4"] //table2.col1

Selecting values present in one column but not in all other columns

Suppose I have columns col1, col2, col3, col4 in myTable and I need to print out the values exclusive to only one column .
So if the above looks like
col1 col2 col3 col4
s e c b
c c a s
n s e a
d d q c
Then the output should be n, q b since they are exclusive only to col1, col3 and col4 respectively.
How can I achieve this through a query in mysql php?
EDIT The duplicates dont have to be in a single row .I have changed the the table layout now to make it clear.
If you are looking for a SQL-only solution, you can do a query per column like this:
SELECT
col1 AS unique_on_col1
FROM table
WHERE col1 NOT IN (SELECT col2 FROM table)
AND col1 NOT IN (SELECT col3 FROM table)
AND col1 NOT IN (SELECT col4 FROM table)
It's possible to combine all four queries with UNION but that may not be necessary depending on what you want to do with the data. Also, this query should not perform very well with large datasets.
One slightly more compact way of getting all of them at once:
select distinct col1
from myTable
where col1 not in (select a.col1
from myTable a join myTable b
on a.col1 = b.col2 or a.col1=b.col3 or a.col1=b.col4)
union
select distinct col2
from myTable
where col2 not in (select a.col2
from myTable a join myTable b
on a.col2 = b.col1 or a.col2=b.col3 or a.col2=b.col4)
union
select distinct col3
from myTable
where col3 not in (select a.col3
from myTable a join myTable b
on a.col3 = b.col1 or a.col3=b.col2 or a.col3=b.col4)
union
select distinct col4
from myTable
where col4 not in (select a.col4
from myTable a join myTable b
on a.col4 = b.col1 or a.col4=b.col2 or a.col4=b.col3)
$sql = "
SELECT DISTINCT 'col1' as descr,col1 as val FROM myTable
UNION
SELECT DISTINCT 'col2' as descr,col2 as val FROM myTable
UNION
SELECT DISTINCT 'col3' as descr,year as val FROM myTable";
$result = #mysql_query($sql, $con) or die(mysql_error());
while($row = mysql_fetch_array($result)) {
$make_array[$row['descr']][]=$row['val'];
}
I'm guessing this should work. Dint try the code out but give this one a shot and let us know.
Try This:
SELECT col1 AS unique_on_col1
FROM table
WHERE col1 NOT IN (SELECT col2 FROM table)
AND col1 NOT IN (SELECT col3 FROM table)
AND col1 NOT IN (SELECT col4 FROM table)

Categories