I want to make 2 mysqli queries. But if there are values in the second query that are Identical to the values yielded from the first query I want to exclude those values from the result set. What I have now only seems to work for 1 identical value. the rest of the identical values are shown. how should I change this? Thanks.
$query1 = $db->query("SELECT colTab1 FROM table1");
while ($result1 = $query1 ->fetch_assoc()) {
$query2 = $db->query("SELECT colTab2 FROM table2 WHERE colTab2 <> $result1[colTab1]");
echo $result1['colTab1']."<br>";
}
while ($result2 = $query2 ->fetch_assoc()) {
echo $result2['colTab2']."<br>";
}
}
Well, you can modify your second query as follows:
SELECT colTab2 FROM table2 WHERE colTab2 NOT IN (SELECT colTab1 FROM table1)
Or maybe you just want to select the UNION of the two tables (which will omit duplicates by default):
SELECT colTab1 FROM table1
UNION
SELECT colTab2 FROM table2
(Note that relying on UNION to omit duplicates between the two recordsets is not quite the same thing, as any duplicates that exist within each recordset will also be omitted; if that is a concern, one can SELECT DISTINCT ... UNION ALL SELECT DISTINCT ... instead).
Just run one query; why bring back data from the database to filter on? Filter in the DB.
SELECT colTab2
FROM table2
WHERE colTab2 NOT IN (
SELECT colTab1
FROM table1
)
Related
I have the PHP code:
$query = mysqli_query($mysqli, "SELECT * FROM `table_1`");
$result = mysqli_num_rows($query);
$queryTwo = mysqli_query($mysqli, "SELECT * FROM `table_2`");
$resultTwo = mysqli_num_rows($queryTwo);
$number = $result + $resultTwo;
return $number;
The point is that sometimes, the $number variable is returning NULL,
when it should not supposed to do that.
I have always rows in those 2 tables, and the returned result should not be NULL, ever.
Is this a correct approach to sum the number of rows from 2 tables? I don`t understand why sometimes I get NULL instead of a number.
Well, I would suggest you to do it like
select ( select count(*) from Table1 ) + ( select count(*) from Table2 )
as total_rows
executing this query and getting the value of total_rows will return you true result
Or you can create a stored procedure to do the same thing. as explained below
CREATE PROCEDURE sp_Test
AS
-- Create two integer values
DECLARE #tableOneCount int, #tableTwoCount int
-- Get the number of rows from the first table
SELECT #tableOneCount = (SELECT COUNT(*) FROM Table1
WHERE WhereClause)
SELECT #tableTwoCount = (SELECT COUNT(*) FROM Table2
WHERE WhereClause)
-- Return the sum of the two table sizes
SELECT TotalCount = #tableOneCount + #tableTwoCount
Why don't you go with only one query like this:
you will have the result directly in one step and it will avoid contacting the DB twice to fetch intermediate result and it will also simplify your program!
SELECT
(select count(*) from table_1)
+
(select count(*) from table_2)
I would like to select different column from different row from the same table with one statement . How will I combine this to be one?
SELECT `shop_lat_log` FROM `customers` WHERE `phoneNumber`='254719401837'
SELECT `delivery_lat_log` FROM `customers` WHERE `phoneNumber`='25472054919'
You could just use each of two current queries as subqueries in one select statement:
SELECT
(SELECT shop_lat_log FROM customers WHERE phoneNumber = '254719401837') AS shop_lat_log,
(SELECT delivery_lat_log FROM customers WHERE phoneNumber = '25472054919') AS delivery_lat_log
FROM dual;
This assumes that each of your two queries returns a single value. If not, then perhaps a UNION would be more appropriate:
SELECT
shop_lat_log AS log_value,
'shop_lat_log' AS log_type
FROM customers
WHERE phoneNumber = '254719401837'
UNION ALL
SELECT
delivery_lat_log,
'delivery_lat_log'
FROM customers
WHERE phoneNumber = '25472054919'
You can use a UNION for that:
SELECT `shop_lat_log` FROM `customers` WHERE `phoneNumber`='254719401837'
UNION
SELECT `delivery_lat_log` FROM `customers` WHERE `phoneNumber`='25472054919'
Note that the second query must have the same number of columns as the first query, and the results will have the first query's column names.
So even though you're selecting the delivery_lat_log column in your second query, the results will be in the shop_lat_log column if you're fetching an associative array.
Use an SQL case statement
select case c.phone_number
when '254719401837'
then c.shop_lat_log
when '25472054919'
then c.delivery_lat_log
end as field
from customer as c
where c.phone_number in ('254719401837', '25472054919')
I have the following query:
SELECT question_code FROM table_questions WHERE question_code IN (1,2,3,111,222);
Here, values (1,2,3,111,222) are coming from PHP array.
The output for the above query is:
question_code
1
2
3
I want the output to be the question_codes which are not in the table and present in the Array.
i.e. I want the output to be question_code which do not exist in the table.
question_code
111
222
I know this problem can be handled in PHP after retrieving the data from the Table. But as I may have large number of tuples, solution which can take care of this thing at query level would be helpful.
You will get the record of SELECT question_code FROM table_questions WHERE question_code IN (1,2,3,111,222); in array and values (1,2,3,111,222) are coming from PHP array.
Use array_diff to compare two arrays and gets the difference.
For reference http://www.w3schools.com/php/func_array_diff.asp
If you want to use plain SQL you have to use a LEFT JOIN:
SELECT c.question_code
FROM (SELECT 1 AS question_code
UNION ALL select 2
UNION ALL SELECT 3
UNION ALL SELECT 111
UNION ALL SELECT 222) AS c
LEFT JOIN table_questions q
ON c.question_code = q.question_code
WHERE
q.question_code IS NULL
you can create the subquery SELECT .. UNION ALL .. dynamically, like this:
<?php
$ids = array(1,2,3);
$subquery = str_repeat('SELECT ? AS q UNION ALL ', count($ids) - 1) . 'SELECT ? AS q';
$sql = <<<SQL
SELECT c.q FROM ($subquery) AS c
LEFT JOIN table_questions q
ON c.q = q.question_code
WHERE
q.question_code IS NULL
SQL;
$stm = $db->prepare($sql);
$stm->execute($ids);
$data = $stm->fetchAll();
?>
but it might not be too pratical... the only alternative is to process the returned question_codes codes in php.
How do you get table name from count query, I have multiple queries and I need to get table name from the query results, here is my query
$myquery = "select count(tb_id) as num_rows from table1; select count(tb1_id) from table2...";
if (myqli_multi_query($connection, $myquery){
..
$row = mysqli_fetch_assoc($result);
$num_rows = $row["num_rows"];
..
}
The query is working fine as I can get the number of rows, but I am unable to link the table name to the number of rows (result)
I have tried this, which executes without error, but unable to get the table name still
select count(tb_id) as num_rows, 'table1' as TableName from table1
You could put an identifier into your query you can refer to later.
$myquery = "select 'table1' as tablename, count(tb_id) as num_rows from table1;
select 'table2' as tablename, count(tb1_id) as num_rows from table2;"
// and so on
You can try mysqli_fetch_field
mysqli_fetch_field($result)->table;
Just add it in to the select or the column name.
Column name:
select count(tb_id) as table1_count from table1; select count(tb1_id) as table2_count from table2.
OR sep column:
(select count(tb_id) as num_rows, 'table1' as tablename from table1)
UNION
(select count(tb1_id), 'table2' from table2...)
UNION.... etc
Edited to add: you are returning sep resultsets; consider UNION above for a single resultset.
I have the following php/mySQL code:
$wp_sql_query_text = "SELECT table1.field1, table1.field2, table1.field3,
table2.field1, table2.field2,table3.field1, table3.field2 from table1
INNER JOIN table2 ON table1.field2=table2.field1
INNER JOIN table3 ON table1.field3=table3.field1
WHERE table1.field1 > SOME_VALUE
ORDER BY table1field1";
echo $wp_sql_query_text;
$get_app_history = mysqli_query($conn,$wp_sql_query_text);
$app_entry = mysqli_fetch_assoc($get_app_history);
//some additional code for initialization of counters and variables
while ($app_entry = mysqli_fetch_assoc($get_app_history)){
//some processing
}
Simply put
1) There are 3 tables - table1, table2 and table3.
2) table1 has 3 fields - field1, field2 and field3.
3) table2 and table3 have 2 fields
each.
After 'echo'ing the sql query, I cut and pasted the sql in my phpmyadmin and records are retrieved only once.
However, on my page, I get the same record retrieved twice.
This is because you are fetching your result twice
$app_entry = mysqli_fetch_assoc($get_app_history); // first fetch
.......some additional code for initialization of kounters and variables.....
while ($app_entry = mysqli_fetch_assoc($get_app_history)) // second fetch with a loop
I would suggest to remove first and keep the loop that you might use in case of multiple results