I have two columns that store values(point values).
How do I select where my given number is between the values in the two columns ?
I hope you can get it by doing this:
Lets your number is $your_number and table name is your_table
So your query would be:
SELECT * FROM your_table WHERE $your_number BETWEEN col1 AND col2;
Or if it is ensured that col1 < col2
SELECT * FROM your_table WHERE $your_number >= col1 AND $your_number <= col2;
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)
SELECT user_id,username,full_name,display_name,profile_pic,email,
fb_id,image1,image2,image3,image4,image5,default_pic,
street_address,locality,country,state,is_verified,is_online,
city,image6,image7,image8,image9,image10,last_login,
IFNULL( (
SELECT STATUS
FROM vidioo_contacts
WHERE (contact_id = '55000'
AND user_id = vu.user_id
)
OR (contact_id = vu.user_id
AND user_id = '55000')),0) AS STATUS,
(3959 * ACOS( COS(RADIANS(0)) * COS(RADIANS(latitude)) *
COS(RADIANS(longitude) - RADIANS(0)) + SIN(RADIANS(0)) *
SIN(RADIANS(latitude)))
) AS distance
FROM vidioo_users vu
WHERE user_id != '55000'
AND gender LIKE
( SELECT CASE WHEN show_me = 'everyone'
THEN '%'
ELSE IF(LENGTH(show_me) < 1, '%', show_me)
END
FROM vidioo_users
WHERE user_id = '55000'
LIMIT 1
)
AND IFNULL(vu.is_deleted,0) != 55000
AND vu.user_id NOT IN (
SELECT DISTINCT contact_id
FROM vidioo_blocked_users
WHERE bloked_by_user = 55000
)
AND DATEDIFF(NOW(),last_login) < 7
ORDER BY last_login DESC
LIMIT 0,20
I wish to apply indexing to this query.
If the table has a multiple-column index then mysql uses leftmost prefix of the index. For example you have following select queries -
`SELECT * FROM tbl_name WHERE col1=val1;
SELECT * FROM tbl_name WHERE col1=val1 AND col2=val2;
SELECT * FROM tbl_name WHERE col2=val2;
SELECT * FROM tbl_name WHERE col2=val2 AND col3=val3;`
If an index exists on (col1, col2, col3), only the first two queries use the index. The third and fourth queries do involve indexed columns, but (col2) and (col2, col3) are not leftmost prefixes of (col1, col2, col3).
In your case you must have to create 3 indexes as
Index_1(user_id, gender, last_login)
Index_2(user_id)
Index_3(bloked_by_user)
NOTE:- Too many indexing slow down INSERT query processing.
For more details Click here
In addition to the other suggestions, change AND DATEDIFF(NOW(),last_login) < 7 to
last_login > NOW() - INTERVAL 7 DAY
What you have hides the column last_login inside a function (DATEDIFF), making it unusable with indexing. Then, also, add
INDEX(last_login)
(It may not help, but it may.)
Also, change
AND vu.user_id NOT IN (
SELECT DISTINCT contact_id
FROM vidioo_blocked_users
WHERE bloked_by_user = 55000
)
to
AND NOT EXISTS( SELECT * FROM vidioo_blocked_users
WHERE bloked_by_user = 55000
AND contact_id = vu.user_id )
Together with
INDEX(bloked_by_user, contact_id) -- in either order
Try adding indexes on these four table columns, It should help:
contact_id,
user_id,
is_deleted,
last_login.
i am trying to run an SQL Query to select all rows from a table and then display the column with the lowest value for each row.
for example, lets start with row1...
columns1, column2, column3, column4
the lowest value for this row is in column3 so i need to echo the column3 value then on row2, column4 has the lowest value so column4 should be displayed for this row.
i did try this code:
$sql="SELECT * from callplanmeta ";
$rs=mysql_query($sql,$conn) or die(mysql_error());
while($result=mysql_fetch_array($rs))
{
$sql2="SELECT *, MIN(NULLIF(".$result["callplanname"].",0)) as number2 from callplandata ";
echo $sql2;
$rs2=mysql_query($sql2,$conn) or die(mysql_error());
while($result2=mysql_fetch_array($rs2))
{
echo $result2["description"].' - '.number_format($result2["number2"],2).'<br><br>';
}
}
however i then realised that it was doing it the wrong way round and only showing the lowest value for 1 row
the column names in the callplandata table match the column callplanname in the callplanmeta table
the columns in the callplandata table are dynamic so they are changing all the time and more are constantly being added
you can also get result with this
SELECT Id,
CASE WHEN COLUMN1 <= COLUMN2 and COLUMN1 <= COLUMN3 THEN COLUMN1
WHEN COLUMN2 <= COLUMN1 and COLUMN2 <= COLUMN3 THEN COLUMN2
ELSE COLUMN3 END AS smallest
FROM table_name
you can get result for any number of columns.
First you will use this
SELECT
GROUP_CONCAT(COLUMN_NAME)
FROM
INFORMATION_SCHEMA.COLUMNS
WHERE
table_name = 'mytable'
AND
ORDINAL_POSITION>2
To retrieve all columns, form it as a string in PHP and then run the following (col1,col2,col3) needs to be replaced with the column_name string that you can form using the previous query.
PHP Code added
From your code I understand two things, first you dont need a while loop for the first query because it would return only one record and you need a while loop for the second query because it would return multiple rows, let me try to make up the code accordingly
<?php
$field_string= $mysqli->query("SELECT GROUP_CONCAT(COLUMN_NAME) AS field_string
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = `callplandata`
AND ORDINAL_POSITION>2")->fetch_object()->field_string;
(The >2 above means this will ignore the first two columns, which in your case seems to be number, description. IF you have more or less fields to be ignored then you can modify this number accordingly)
You can then use this field_string value into your other query that needs to find the least
$sql2="SELECT LEAST(".$field_string.") AS number FROM `callplandata`";
$rs2=mysql_query($sql2,$conn);
while($result2=mysql_fetch_array($rs2))
{
echo $result2["number"].'<br>';
}
?>
This will give you the lowest among all the columns other than the first two columns for all the rows and echo it on screen. I am not a PHP programmer, so just about made up the code in PHP, there could be minor errors.
You can solve this puzzle this approach:
SELECT
(SELECT columns1 from myTable) as myField
UNION
(SELECT column2 from myTable)
UNION
(SELECT column3 from myTable)
order by myField ASC LIMIT 1
I would like some help that has had me stumped for two days. I need to retrieve data from a database and order it by column1 when it isn't empty and then the rest of the result by column2
column1 column2
1 11
2 12
3 13
14
15
16
Required result
1,2,3,14,15,16
I've tried numerous approaches, my latest failed attempt being
$SQL = "SELECT * FROM table ORDER BY COALESCE(column1, column2) DESC";
and
$SQL = "SELECT * FROM table ORDER BY COALESCE(column1, column2) ASC";
My above SQL is returning NULL value column1 above column2
This should work:
$SQL = "SELECT * FROM table ORDER BY COALESCE(NULLIF(Other,''), column2) DESC";
I saw it here: SQL Coalesce with empty string
coalesce() would only work if the "empty" values in column1 are actually NULL. Empty strings will not trigger a coalesce() operation.
Beyond that, your query will NOT work. You cannot do a select * with two columns and somehow magically get one single column in the result. For this you'll need a UNION query:
(SELECT column1 AS col FROM yourtable)
UNION ALL
(SELECT column2 AS col FROM yourtable)
ORDER BY col
If you want 1 column, you could try a combination of NULLIF and COALESCE, that should account for both empty and null values
SELECT COALESCE(NULLIF(column1, ''), column2) AS COL
FROM table
SQLFiddle Demo
In case you actually want all of the numbers on a single result row, separated by commas, you can use GROUP_CONCAT along with the previous code:
SELECT GROUP_CONCAT(COALESCE(NULLIF(column1, ''), column2)) AS col
FROM table
SQLFiddle Demo2
Old question but this solution worked for me:
$SQL = "SELECT * FROM table ORDER BY COALESCE(NULLIF(column1, ''), column2)";
You should be able to use CASE like so:
SELECT *
FROM table
ORDER BY
CASE WHEN LENGTH(column1) IS >0 THEN column1
ELSE column2 END
ASC
http://dev.mysql.com/doc/refman/5.0/en/case.html
How do I know which column matched if I have two LIKE clauses for two different columns and eventually one of the two columns contains the needle.
you could do something like:
SELECT 1 AS `match`, * FROM `table` WHERE col1 LIKE 'needle%'
UNION
SELECT 2 AS `match`, * FROM `table` WHERE col2 LIKE 'needle%'
and use match to know
Note: this could probably be written with a IF()
SELECT
IF(col1 LIKE 'needle%' AND col2 LIKE 'needle%', 0, IF(col1 LIKE 'needle%', 1, 2)
AS match,
*
FROM
table
WHERE
col1 LIKE 'needle%'
OR
col2 LIKE 'needle%'
match teklls you which colums hit:
0 = both
1 = match on col1
2 = match on col2
You can use your PHP section to check which one matched.
if (stristr($result['col1'], $queryvar) === true) // col1 matched