Here's my situation: I need to select all the messages where user_id = x OR y OR z.
I have an array in PHP:
users = ('1', '2', '3')
is there anyway to select all the messages where user_id = one of those values without having a massive query of:
user_id = '1' OR user_id = '2' OR user_id = '3?'
(I need to receive the messages of 100+ people so it would be inefficient)
Thanks
Use an IN clause.
SELECT *
FROM YourTable
WHERE user_id IN ('1','2','3')
Yes! You can use the IN operator:
user_id IN ('1', '2', '3')
If your array will always be safe and contain elements, you can do:
"user_id IN ('" . implode("', '", $users) . "')"
in PHP, too.
This is easy to do :
$query = "SELECT * FROM table_name WHERE user_id IN('1','2','3')";
Since your value is in array you can use:
$users = array('1', '2', '3');
$user_id = "'" . implode("', '", $users ) . "'";
$query = "SELECT * FROM table_name WHERE user_id IN($user_id)";
Hope this helps.
Probably you don't like IN keyword. Instead, you can use a regular expression like this:
select * from your_table where user_id regexp '1|2|3'
user_id >= 1 AND <= 3
Is one alternative.
before strings ids are:
$query = "SELECT * FROM table_name WHERE user_id IN('1','2','3')";
preformance int for ids:
$query = "SELECT * FROM table_name WHERE user_id IN(1,2,3)";
Related
This question already has an answer here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Closed last year.
I have a query to group by id, sum, and then rank. The issue is that the table contains all classes and doesn't have a column to define the class of each data.
Therefore, I have to use another table to get the id's that are in the same class as the id being ranked and then compare them.
Here is the code that I have already tried but results to errors:
$que = "SELECT * FROM registration WHERE CurrentClass = (SELECT CurrentClass FROM registration WHERE AdmNo = '$user_id')";
$statemen = $connect->prepare($que);
$statemen->execute();
$res = $statemen->fetchAll();
foreach($res as $rowww) {
$resu1 = mysqli_query($conn, "SELECT AdmNo, rank, total_score
FROM (SELECT * WHERE AdmNo = '".$rowww['AdmNo']."', IF(#marks=(#marks:=total_score), #auto, #auto:=#auto+1) AS rank
FROM (SELECT * FROM
(SELECT AdmNo, SUM(Score) AS total_score
FROM `{$examination}`,
(SELECT #auto:=0, #marks:=0) as init
GROUP BY AdmNo) sub ORDER BY total_score DESC)t) as result
WHERE AdmNo = '$user_id'");
$row1 = mysqli_fetch_assoc($resu1);
$sum = $row1['total_score'];
$position = $row1['rank'];
$totalMarks = round($sum, 2);
}
To my understanding, the error
Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, bool given in E:\xampp\htdocs\user...
Is because of the multi-row returned in the first query and that's why I need help with how I can solve this problem.
The required result are that the AdmNo's selected from registration are the only one that should be used in ranking.
Try this:
$query = "SELECT AdmNo, rank, total_score FROM (
SELECT * WHERE AdmNo = '" . $rowww['AdmNo'] . "', IF(#marks=(#marks:=total_score), #auto, #auto:=#auto+1) AS rank FROM (
SELECT * FROM (
SELECT AdmNo, SUM(Score) AS total_score FROM `" . $examination . "`, (
SELECT #auto:=0, #marks:=0
) as init GROUP BY AdmNo
) sub ORDER BY total_score DESC
) t
) as result WHERE AdmNo = '" . $user_id . "'";
$resu1 = mysqli_query($conn, $query);
I have a column in my table called to_user that the content of it like this:
id to_user
1. 1+2+3
2. 1
my query
select
* from notifications
where (type = 4 and to_user LIKE %+".$user_id."+%)
or (to_user REGEXP +?".$user_id."+? ) and status = 2
but it doesn't work .
you should enclose the strig for search in proper quotes (and remove + if is not part oth string of you sarch condition )
"select * from notifications where (type = 4 and to_user LIKE '%".$user_id."%')
or (to_user REGEXP '".$user_id."' ) and status = 2" ;
due the fact you are using string if you n need an exact macth is = istead of like and don't use regex too
$sql = "SELECT *
FROM notifications
WHERE (type = 4 and to_user
LIKE '%" . $user_id . "%')
OR (to_user REGEXP '\+" . $user_id . "\+' )
AND status = 2";
How to not exist on another table on this two table?
Users table
User_relationships table
and this is my current query
"SELECT * FROM `users`
WHERE CONCAT(first_name, " ", last_name) LIKE '%' . $name . '%'
AND (`role_id` = 6 OR `role_id` = 4)
ORDER BY `first_name` asc limit 15"
and I want to add on query where guardian_id(user_id) not exist on the user_relationships table
UPDATE 1
select * from `users`
where not exists
(select 1 from `user_relationships`
inner join `users` on `user_relationships`.`guardian_id` = `users`.`id`
where `user_relationships`.`student_id` = 422)
I tried this and still returns me zero result.
I only have var name = ? and student_id = ?
try to use "NOT IN" query function with 'DISTINCT'.
following may help you.
select * from users where CONCAT(first_name, " ", last_name) LIKE '%' . $name . '%' and (role_id= 6 or role_id= 4) and (id NOT IN (select DISTINCT guardian_id from User_relationships where student_id = $student_id)) order by first_name ASC limit 15
Let me know if you still need some changes.
I have a lot of articles tagged with the tag "dog". I have a new tag now called "cat". I want to add the tag "cat" to all articles that already have the tag "dog". A few articles have both tags. I don't want to retag these with "cats".
In other words, if an article has the tag "dog" and doesn't yet have the tag "cat" I want to add the tag "cat" to it. Here is the script I wrote:
<?php
# Get "cat" tag id
$sql = "SELECT `id`
FROM tags
WHERE name = 'cat'
LIMIT 1";
$cat_tag = mysql_fetch_assoc(mysql_query($sql));
# Get "dog" tag id
$sql = "SELECT `id`
FROM tags
WHERE name = 'dog'
LIMIT 1";
$dog_tag = mysql_fetch_assoc(mysql_query($sql));
######################################
# Get all nodes tagged with "dog"
$sql = "SELECT `node_id`
FROM node_tags
WHERE `tag_id` = '" . $dog['id'] . "'";
$query = mysql_query($sql);
while($row = mysql_fetch_assoc($query)) {
# Check to see if current node has "cat" tag already
$sql = "SELECT COUNT(*)
FROM node_tags
WHERE `node_id` = '" . $row['node_id'] . "'
AND `tag_id` = '" . $cat['id'] . "'";
$check_already_exists = mysql_fetch_assoc(mysql_query($sql));
# If node doesn't already have "cat" tag, then add it
if($check_already_exists == '0') {
$sql = "INSERT INTO `node_tags`(node_id, tag_id)
VALUES('" . $row['node_id'] . "', '" . $cat['id'] . "')";
mysql_query($sql);
}
}
?>
I want to be able to run this directly from my MySQL manager tool. So it can't have any PHP but should be one large SQL query. How to do this?
The following query gets all "dogs" that have no cat id. It then inserts them into the table:
insert into node_tags(node_id, tag_id)
SELECT id, $cat['id']
FROM tags t join
node_tags nt
on t.node_id = nt.node_id
WHERE t.name = 'dog'
group by id
having max(case when tag_id = $cat['id'] then 1 else 0 end) = 0
You can't do this in one query, because you would need to insert data that depends on selecting data from the same table. The closest you can get is something like this, assuming you have a unique key defined on (node_id,tag_id):
CREATE TEMPORARY TABLE `tmp` (`node_id` TEXT, `tag_id` TEXT); # Choose better column types if possible
INSERT INTO `tmp` SELECT `node_id`, `tag_id` FROM `node_tags`;
SET #id_cat = (SELECT `id` FROM `tags` WHERE `name`='cat'),
#id_dog = (SELECT `id` FROM `tags` WHERE `name`='dog');
INSERT IGNORE INTO `node_tags` (`node_id`, `tag_id`)
SELECT `node_id`, #id_cat FROM `tmp` WHERE `tag_id`=#id_dog
UNION
SELECT `node_id`, #id_dog FROM `tmp` WHERE `tag_id`=#id_cat;
DROP TABLE `tmp`;
You can paste this into your MySQL manager tool and it should work.
You can make a insert based in a select clause:
INSERT INTO node_tags (node_id, tag_id)
SELECT node_id, (SELECT MAX(id) FROM tags WHERE name = 'cat')
FROM node_tags
WHERE tag_id = (SELECT MAX(id) FORM tags WHERE name = 'dog')
Make a backup before you try something like that ;)
Try this query. I havn't tested this. But I think this will work.
INSERT into node_tags(node_id, tag_id)
( SELECT node_id, tag_id
FROM node_tags nt , tags t
where t.id = nt.tag_id AND t.name = 'dog'
AND nt.node_id NOT IN (SELECT t1.id FROM node_tags nt1, tags t1
where nt1.node_id = nt.node_id AND t1.id = nt1.tag_id AND t1.name = 'cat')
)
First change your table and make (node_id and tag_id) together UNIQUE, because that's what it seems that you need.
ALTER TABLE `node_tags` ADD UNIQUE (`node_id`,`tag_id`);
this is your query:
$sql = "INSERT IGNORE INTO `node_tags`
SELECT (SELECT `node_id` FROM node_tags WHERE EXISTS (SELECT tags.* FROM tags WHERE node_tags.`tag_id` = tags.`id` AND tags.name = 'dog') LIMIT 1),
(SELECT `id` FROM tags WHERE name = 'cat' LIMIT 1)";
I'm trying to make a search for a property website i'm working on for a friend.
In the Database the property types are named by id numbers, ie: house = 30, flat = 8, terraced =1, and so forth..
How can i retrieve ALL properties from the database when some are detached houses with value of 2 and houses are value of 30 etc :)
It has got me stuck..lol
Here's what i have so far which isn't working...
$bedrooms = $_GET['bedrooms'];
$pricefrom = $_GET['pricefrom'];
$priceto = $_GET['priceto'];
$proptype = $_GET['proptype'];
if($proptype == 'house'){
$search_propsubid = array('1,2,3,4,5,6,21,22,23,24,26,27,30');
}elseif($proptype == 'flat'){
$search_propsubid = array('7,8,9,10,11,28,29,44');
}elseif($proptype == 'bungalow'){
$search_propsubid = array('');
}
$sql = mysql_query("SELECT * FROM `properties` WHERE `PROP_SUB_ID`='$search_propsubid' AND `BEDROOMS`='$bedrooms' AND `TRANS_TYPE_ID`='1' HAVING `PRICE` BETWEEN '$pricefrom' AND '$priceto' ORDER BY `UPDATE_DATE` DESC");
Thank you for your time i hope someone can point me in the right direction..
Regards
Steve
You can try to implode array:
$search_propsubid = array('1,2,3,4,5,6,21,22,23,24,26,27,30');
$comma_separated = implode(",", $search_propsubid);
$sql = mysql_query("SELECT * FROM `properties` WHERE `PROP_SUB_ID` in ($comma_separated) ...
Comme back with news if this don't works for you.
You can use the MySql IN() comparison operator to select all that match the list of values:
$sql = mysql_query("
SELECT *
FROM `properties`
WHERE `PROP_SUB_ID` IN (" .implode(",", $search_propsubid). ")
AND `BEDROOMS`='$bedrooms'
AND `TRANS_TYPE_ID`='1'
HAVING `PRICE` BETWEEN '$pricefrom' AND '$priceto'
ORDER BY `UPDATE_DATE` DESC
");
Assuming $proptype == 'flat', the output will be:
SELECT *
FROM `properties`
WHERE `PROP_SUB_ID` IN (7,8,9,10,11,28,29,44)
...