php/mysql Merge 2 tables with same Columns correctly - php

EDIT: Thanks For JoseCarlosPB here is the solution:
SELECT
(select count(DISTINCT userscount) AS duplicates from users1)
+
(select count(DISTINCT userscount) AS duplicates from users2) AS duplicates
FROM dual;
So i have 2 tables and a mysql statement i want to merge 2 tables but there is same column in both.I think There is nothing to do in PHP code i think the problem is in the mysql statement.
my code works(no errors) but it gives unexpected output.i simply want to correctly count userscount here is what i mean:
table1 has 32 users and table2 has 44 users
i thought the output will be 76 users but it is 3244
PHP:
include 'conn00.php';
$sql = "select DISTINCT userscount, count(DISTINCT userscount) AS duplicates from users1 UNION ALL
select DISTINCT userscount, count(DISTINCT userscount) AS duplicates from users2";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row["duplicates"];
}
} else {
}
table1:
users1
32
table2:
users2
44
output: 3244 i want the output to be 76
If the solution is in mysql will be better bcz i have more similar sql statements and i want apply the solution for all of it.
thanks for answering

I think you can do it this way, almost like alistaircol said
SELECT
(select count(DISTINCT userscount) AS duplicates from users1)
+
(select count(DISTINCT userscount) AS duplicates from users2) AS duplicates
FROM dual;

Please check article you need Combine two MYSQL table with same column Name
Just comparing to this you need to move count outside of UNION in order to work as you expected

Maybe you could try something like this for your query:
SELECT
(select count(DISTINCT userscount) AS duplicates from users1 group by usercount)
+
(select count(DISTINCT userscount) AS duplicates from users2 group by usercount)
FROM dual;
DUAL is purely for the convenience of people who require that all SELECT statements should have FROM and possibly other clauses. MySQL may ignore the clauses. MySQL does not require FROM DUAL if no tables are referenced.
More info about DUAL: https://dev.mysql.com/doc/refman/8.0/en/select.html

maybe you can change your code query into this to sum the entire counting value
include 'conn00.php';
$sql = "select sum(i) as duplicates from (
select count(DISTINCT userscount) as i from users1 union all
select count(DISTINCT userscount) as i from users2
) x";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row["duplicates"];
}
} else {
}

I am not sure, if the semantics of the query was correct, but the syntax must be like this (WHERE clause goes after JOIN and ON):
SELECT users1.text1, users2.name,users2.email,
users1.username
FROM users1
INNER JOIN users2
ON users1.text1=users2.text1
WHERE users1.username = $_SESSION[username]

SELECT * from
( (select count(DISTINCT userscount) AS duplicates from users1)
union all
(select count(DISTINCT userscount) AS duplicates from users2)
) as duplicates
You can also merge in this way.hope it was helpful

Related

Find duplicate value accross multiple column within same row in Mysql

Please help find duplicate entries in multiple columns of same row in MySQL:
If you want to find the records that have duplicates in columns you can use this query:
SELECT T1.* FROM tbl T1
JOIN
(SELECT id
FROM (
SELECT id, sample1 AS n from tbl
UNION ALL
SELECT id, sample2 AS n from tbl
UNION ALL
SELECT id, sample3 AS n from tbl
) AS X
GROUP BY id, n
HAVING COUNT(*) > 1
) T2
ON T1.id = T2.id;
You can also test it Here
I am not sure with MySql,
But in PHP below example will use.
Example
$query = "select * from table_name";
$result = mysqli_query($query);
while ($row = mysqli_fetch_array($result)) {
if ($row['sample1'] == $row['sample2']) {
// This row duplicate
}
else {
// This row not duplicate
}
}
SELECT Sample1, COUNT(*) C FROM tablename GROUP BY Sample1 HAVING C > 1;
Finding duplicate values in MySQL
MySQL select records for duplicates using multiple columns

how to select and sum in single sql query

Is it possible or another solution to sum and select multiple rows in single sql query and print with while looping like that:
$query = mysql_query("SELECT SUM(Total), * FROM table");
while ($fetch = mysql_fetch_row($query)) {
echo $fetch[a];
echo $fetch[b];
echo $fetch[c];
}
Use a JOIN with a subquery that calculates the total.
SELECT SumTotal, a.*
FROM Table a
JOIN (SELECT SUM(Total) SumTotal
FROM Table) b
Do you mean this?
SELECT (SELECT SUM(Total) FROM `table`) totalSum, a.* FROM `table` a
you can do it as what #491243 suggested
SELECT (SELECT SUM(Total) FROM `table`) AS totalSum, * FROM `table`
But this is not recommended because this will cause that SQL Engine calculate sum of the column total on each row it's selecting from the database and sending a new column with the results to php with identical values in the column totalSum fields ,
better go for 2 queries.
one for selecting the rows and the other to get the total
We can use CROSS APPLY for calculation.
SELECT SumTotal, A.*
FROM table A
CROSS APPLY (SELECT SUM(Total) SumTotal FROM Table) B
Make use of GROUP BY clause.
$query = mysql_query("SELECT *,SUM(Total) as TotalSUM FROM table GROUP BY Total");
while ($fetch = mysql_fetch_row($query)) {
echo $fetch[a];
echo $fetch[b];
echo $fetch[c];
}
Usually you want to group by a column so that you can sum by a group and then it will give you separate rows for each category_id in this example
SELECT category_id, SUM(price) as totalprice
FROM products
GROUP BY category_id
isn't it simpler and faster to sum inside the loop instead using complex query ?
you could just make simple (faster) select * from table and in your while loop make the sum while looping. it will be faster than making query with subquery

PHP SQL JOIN Avoid ID Duplicates

I am using this code:
SELECT * FROM Table1
JOIN Table2 USING(venue_id)
WHERE table2.location = '$MyVariable'
Then to count the number of records return:
$num_rows = mysql_num_rows($result);
echo "$num_rows";
It works great but venue_id in Table1 has lots of entries and I only want it to get one per venue_id
How can I make it so it only returns 1 venue_id instance?
Use GROUP BY clause,
SELECT * FROM Table1
JOIN Table2 USING(venue_id)
WHERE table2.location = '$MyVariable'
GROUP BY `Table1`.`venue_id`

How to get in MySQL defined names into php?

If I have a mysql query like
(SELECT COUNT(*) FROM data AS amount)
UNION
(SELECT COUNT(*) FROM data WHERE some < 50 AS something)
and then create an array with php like this $row = mysqli_fetch_array($sql, MYSQLI_ASSOC);.
How can I now address each of the AS names. This does not work: echo $row["amount"];. The second question I have is why can't I use AS something when having a WHERE clause?
Try this:
(
SELECT
'amount1' as za_name,
COUNT(*) as za_count
FROM
data
)
UNION
(
SELECT
'amount2' as za_name,
COUNT(*) as za_count
FROM
data
WHERE some < 50
)
Then you can differentiate by $row[za_name] and get the amount $row[za_count]
For the second question : you can use it if you make a temp table :
SELECT
tmp.za_name,
tmp.za_count
FROM (
SELECT
'amount2' as za_name,
COUNT(*) as za_count
FROM
data
WHERE some < 50
) as tmp
In a UNION the row names/aliases for the entire query are whatever they are in the first query.
So if you have
SELECT field1 AS A
UNION
SELECT field2 AS B
Your final result will only have an A field, which will have both field1 and field2.
In your query, you want to alias the COUNT(*), not the table.
(SELECT COUNT(*) AS amount FROM data)
UNION
(SELECT COUNT(*) FROM data WHERE some < 50)
Nor $row['amount'] will be all of the COUNT(*) rows from the entire query.
in your query
(SELECT COUNT(*) FROM data AS amount) UNION (SELECT COUNT(*) FROM data WHERE some < 50 AS something)
You are aliasing the table data to the name amount rather than the sub-query
You have to edit the query this way (aliases on the columns, too)
(SELECT COUNT(*) as amount FROM data)
UNION
(SELECT COUNT(*) as amount FROM data WHERE some < 50 AS something)
This way You are able to address $result['amount'] as a result from the fetch assoc method.

SQL Union only counting one query

Im trying to count rows in a table. Currently im using this:
$sql = "SELECT COUNT(*)
FROM `friends`
WHERE `user1`='".$user1."'
AND `user2`='".$user2."'
AND `valid`=0
UNION
SELECT COUNT(*)
FROM `friends`
WHERE `user1`='".$user2."'
AND `user2`='".$user1."'
AND `valid`=0";
As you see, user1 can be both $user1 AND $user2. but it does not count the rows after the UNION, it only does the first query before UNION so im ending up with 0 when i actually should be counting 1 row.
How do I solve this?
Another alternative, replace your query with this:
$sql = "SELECT COUNT(*)
FROM `friends`
WHERE (
(`user1`='".$user1."' AND `user2`='".$user2."') OR
(`user1`='".$user2."' AND `user2`='".$user1."')
)
AND `valid`=0";
Your query is actually returning 2 records - 0 for the first count and 1 for the second. You could use a sub-query to SUM() your results...
$sql = "SELECT SUM(A) AS COUNT FROM
(SELECT COUNT(*) AS A
FROM `friends`
WHERE `user1`='".$user1."'
AND `user2`='".$user2."'
AND `valid`=0
UNION
SELECT COUNT(*)
FROM `friends`
WHERE `user1`='".$user2."'
AND `user2`='".$user1."'
AND `valid`=0
)";
Use UNION ALL instead. UNION will exclude duplicate rows.
You can use an even simpler solution:
SELECT COUNT(*)
FROM friends
WHERE
$user1 IN (user1,user2) AND
$user2 IN (user1,user2) AND
valid = 0

Categories